printf %q应该引用一个字符串。但是,当执行到脚本中时,它会删除空格。
这个命令:
printf %q "hello world"
产出:
hello\ world
这是正确的。
这个脚本:
#!/bin/bash
str="hello world"
printf %q $str
产出:
helloworld
这是错误的。
如果这种行为确实是预期的,那么脚本中有什么替代方法来引用包含任何字符的字符串,以便被调用的程序将其转换回原始字符?
谢谢。
软件: GNU,版本4.1.5(1)-release (i 486-pc-linux-gnu)
编辑:解决了,谢谢。
发布于 2012-01-28 11:49:39
你应该使用:
printf %q "$str"
示例:
susam@nifty:~$ cat a.sh
#!/bin/bash
str="hello world"
printf %q "$str"
susam@nifty:~$ ./a.sh
hello\ world
运行printf %q $str
时,shell将其展开为:
printf %q hello world
因此,字符串hello
和world
作为两个独立的参数提供给printf
命令,并并排打印两个参数。
但是,当您运行printf %q "$str"
时,shell将其扩展为:
printf %q "hello world"
在这种情况下,字符串hello world
作为一个参数提供给printf
命令。这就是你想要的。
下面是一些您可以尝试使用这些概念的东西:
susam@nifty:~$ showargs() { echo "COUNT: $#"; printf "ARG: %s\n" "$@"; }
susam@nifty:~$ showargs hello world
COUNT: 2
ARG: hello
ARG: world
susam@nifty:~$ showargs "hello world"
COUNT: 1
ARG: hello world
susam@nifty:~$ showargs "hello world" "bye world"
COUNT: 2
ARG: hello world
ARG: bye world
susam@nifty:~$ str="hello world"
susam@nifty:~$ showargs $str
COUNT: 2
ARG: hello
ARG: world
susam@nifty:~$ showargs "$str"
COUNT: 1
ARG: hello world
发布于 2012-01-28 11:50:57
试一试
printf %q "${str}"
在你的剧本里。
https://stackoverflow.com/questions/9045001
复制相似问题