打印包含单引号和其他特殊字符的字符串

bat*_*til 8 command-line shell scripting awk quoting

我怎样才能用 AIX 脚本正确地写这个?我的要求是在 test.txt 中写这个命令:

clock=$(prtconf -s | awk '{print $4,$5}')
Run Code Online (Sandbox Code Playgroud)

我试过这个命令:

print 'clock=$(prtconf -s | awk '{print $4,$5}')' > test.txt
Run Code Online (Sandbox Code Playgroud)

写在 test.txt 中的输出给了我:

clock=$(prtconf -s | awk {print ,})
Run Code Online (Sandbox Code Playgroud)

如果我使用" "引号:

print "clock=$(prtconf -s | awk '{print $4,$5}')"
Run Code Online (Sandbox Code Playgroud)

它直接让我:

clock=3612 MHz
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Mat*_*Mat 5

您需要继续使用单引号,然后在输出中“单独”打印出您需要的单引号,或者使用双引号并转义美元符号。

对于第二个选项:

print "clock=\$(prtconf -s | awk '{print \$4,\$5}')" > test.txt
Run Code Online (Sandbox Code Playgroud)

为了第一:

print 'clock=$(prtconf -s | awk '\''{print $4,$5}'\'')' > test.txt
Run Code Online (Sandbox Code Playgroud)

'text'然后转义单引号\'然后'other text'。)

为了完整起见,请注意print扩展反斜杠字符转义序列(这在您的情况下无关紧要,因为您要打印的字符串不包含任何反斜杠)。为避免这种情况,请使用print -r.


Gil*_*il' 5

这样做的简单方法是'…'在字符串周围使用单引号。单引号分隔文字字符串,因此您可以在它们之间放置任何内容,但单引号除外'。要在字符串中插入单引号,请使用四字符序列'\''(单引号、反斜杠、单引号、单引号)。

从技术上讲,无法将单引号放在单引号文字中。然而,连续文字与单个文字一样好。'foo'\''bar'被解析为

  1. 单引号文字 foo
  2. 反斜杠引用的文字字符 '
  3. 单引号文字 bar

这实际上意味着这'\''是一种在单引号文字中转义单引号的方法。

请注意,kshprint命令执行反斜杠扩展。添加-r选项以避免这种情况。它不会伤害您,因为您要打印的字符串中恰好没有反斜杠,但最好使用-r,以防在维护期间添加反斜杠。

print -r -- 'clock=$(prtconf -s | awk '\''{print $4,$5}'\'')' > test.txt
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用 POSIX 方法逐字打印字符串,并在末尾添加换行符:

printf '%s\n' 'clock=$(prtconf -s | awk '\''{print $4,$5}'\'')' > test.txt
Run Code Online (Sandbox Code Playgroud)