简体   繁体   English

jq-如何在shell脚本中转​​义'*'(特殊字符)?

[英]jq - How to escape ' * ' (special character) in shell script?

Im using the following command in shell script 我在shell脚本中使用以下命令

echo $(jq -n '"1\n2\n3" | gsub("\n"; @t " * ")')

and the expected output is 预期的输出是

"1 * 2 * 3" 

But in shell script it replaces '\\n' with all the file names in the respective directory (ie '*' is treated as a special parameter in this context). 但是在shell脚本中,它将用相应目录中的所有文件名替换“ \\ n”(即,在此上下文中,“ *”被视为特殊参数)。

1 file1 file2 2 file1 file2 3

When we execute the same in a terminal it gives the expected output. 当我们在终端中执行相同的操作时,它将给出预期的输出。

Can anyone help me in this? 有人可以帮我吗?

You need to quote the command substitution to prevent the result ( 1 * 2 * 3 ) from undergoing pathname expansion. 您需要引用命令替换,以防止结果( 1 * 2 * 3 )经历路径名扩展。

echo "$(jq -n '"1\n2\n3" | gsub("\n"; @t " * ")')"

Keep in mind, though, that there is no reason capture the output of a command if the only thing you do with it is pass it as the lone argument to echo . 但是请记住,如果您执行命令的输出是将其作为echo的唯一参数传递,则没有理由捕获命令的输出。 Just let the command run by itself. 只需让命令自己运行即可。

$ echo "$(jq -n '"1\n2\n3" | gsub("\n"; @t " * ")')"
"1 * 2 * 3"
$ jq -n '"1\n2\n3" | gsub("\n"; @t " * ")'
"1 * 2 * 3"

(As a bonus, jq will probably produce colored output if you aren't capturing the output.) (作为奖励,如果您不捕获输出, jq可能会产生彩色输出。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM