我是 awk 的新手。我只是尝试写一些东西来交换我的文本文件。但我失败了。
我想像'hello'
.
我用命令awk '{print "'hello'"}' filename
来做它。但是失败了:
输出像:你好
,但我用命令awk '{print "\'hello\'"}' filename
做它。再次失败:
输出像:>
ok。看来awk命令没有得到我的意思。所以我对此感到困惑。如何解决这个问题。
伙计们谢谢。
使用ASCII码:
awk '{print "\x27" "hello" "\x27"}' filename
使用变量:
awk -v q="'" '{print q "hello" q}' filename
例子:
$ seq 2 > filename
$ awk '{print "\x27" "hello" "\x27"}' filename
'hello'
'hello'
$ awk -v q="'" '{print q "hello" q}' filename
'hello'
'hello'
awk '{print "'"'"'hello'"'"'"}' filename
只需使用双引号:
awk "{print \"'hello'\"}" filename
尽管这不会真正修改您的文件。
clyfish 的答案有效,如果你必须让它输出单引号并且你必须使用你在命令行上传递的脚本。
What I usually do in cases like these, though, when I need to do quoting but I don't want to write a 'real' awk script, is this:
awk 'function q(word) { return "\"" word "\"" }
{ printf("mv %s SomeDir/;", q($0)) }'
What I've done is to define a function that returns whatever you pass it in double quotes. Then use printf to actually use it. Without doing that, I would have had to do:
awk '{ print("mv \"" $0 "\" SomeDir/;") }';
It gets pretty nasty. For more complicated examples, this can be a life saver.
However, suppose you really do need to output something with actual single quotes. In that case dealing with odd shell quoting rules while trying to pass scripts like this on the command line is going to drive you completely insane, so I would suggest you just write a simple throwaway file.
#!/usr/bin/awk
# hi.awk
{ print("'hello'") }
then call it:
awk -f ./hi.awk
You don't really even need the #!
line in the file if you do it that way, but neither does it hurt.