[英]Bash: “printf %q $str” deletes spaces when in scripts. (Alternatives?)
printf%q应该引用一个字符串。 但是,当执行到脚本中时,它会删除空格。
这个命令:
printf %q "hello world"
输出:
hello\ world
哪个是对的。
这个脚本:
#!/bin/bash
str="hello world"
printf %q $str
输出:
helloworld
这是错的。
如果确实需要这样的行为,那么在脚本中有什么替代方法可以引用包含任何字符的字符串,以便可以通过被调用的程序将其转换回原始字符?
谢谢。
软件:GNU bash,版本4.1.5(1)-release(i486-pc-linux-gnu)
编辑:解决了,谢谢。
你应该使用:
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
尝试
printf %q "${str}"
在你的脚本中。
这对我有用。 满足这些要求
#! /bin/bash FOO='myTest3$; t%^&;frog now! and *()"' FOO=`printf "%q" "$FOO"` # Has \ chars echo $FOO # Eat all the \ chars FOO=$(printf "%q" "$FOO" | sed "s/\\\\//g") # Strip \ chars echo $FOO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.