我有一些重新安排线路的awk。我想逃避其中一个变量(例如$ _),这样就可以用反斜杠转义"
和\
。
示例:
echo "Ehm, \"hi\", he \\ said" | awk '{$1="" ; print "\"" $_ "\"" }'
" "hi", he \ said"
(不要更改回声,通常我从其中有Ehm, "hi", he \ said
的文件中读取。
我想
" \"hi\", he \\ said"
代替。我怎样才能做到这一点? awk中是否有可以执行此操作的功能?
答案 0 :(得分:2)
你有理由诉诸awk吗? Bash完全能够执行字符串操作:
#!/bin/bash
read -r ignored line <<<'Ehm, "hi", he \ said'
line=${line//\\/\\\\}
line=${line//\"/\\\"}
echo $line
<强>输出强>
\"hi\", he \\ said
答案 1 :(得分:2)
这是你正在寻找的吗?
$ cat tst.awk
function foo(str) {
sub(/^[^[:space:]]+/,"",str) # remove first field
gsub(/["\\]/,"\\\\&",str) # put \ before each \ and "
return "\"" str "\"" # surround with quotes
}
{ print foo($0) }
测试:
$ echo "Ehm, \"hi\", he \\ said" | awk -f tst.awk
" \"hi\", he \\ said"
$ cat file
Ehm, "hi", he \ said
$ awk -f tst.awk file
" \"hi\", he \\ said"
答案 2 :(得分:1)
当您使用Bash传递字符串时,您必须考虑使用双引号执行的echo
本身。在这里找到它:
$ echo "Ehm, \"hi\", he \\ said" | awk '1'
Ehm, "hi", he \ said
使用单引号解决了部分问题:
$ echo 'Ehm, \"hi\", he \\ said' | awk '1'
Ehm, \"hi\", he \\ said
这就是说,现在是时候在字符串周围添加引号了。为此,我们使用print
三个参数 - &gt; print "\"", $0, "\""
。
要删除第一个字段,我们可以in the correct way:
$ echo 'Ehm, \"hi\", he \\ said' | awk '{sub(/^\S+\s*/, ""); print "\"", $0, "\""}'
"\"hi\", he \\ said"
如果我们将其删空,看起来我们得到了您想要的输出:
$ echo 'Ehm, \"hi\", he \\ said' | awk '{$1=""; print "\"", $0, "\""}'
" \"hi\", he \\ said"