Bash:“printf%q $str”在脚本中删除空格. (备择方案?)
发布时间:2020-12-15 18:46:55 所属栏目:安全 来源:网络整理
导读:printf%q应该引用一个字符串.但是,当执行到脚本中时,它会删除空格. 这个命令: printf %q "hello world" 输出: hello world 哪个是对的. 这个脚本: #!/bin/bashstr="hello world"printf %q $str 输出: helloworld 这是错的. 如果这样的行为确实是预期的
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: %sn" "$@"; } 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |