如何使用awk转义反斜杠和双引号 [英] How to escape backslash and double quotes with awk
本文介绍了如何使用awk转义反斜杠和双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有些awk重新排列了一行.我想转义变量之一(例如$ _),使"
和\
用反斜杠转义.
I have some awk that rearrange a line. I would like to escape one of the variables (e.g. $_), in such way that "
and \
are escaped with a backslash.
示例:
echo "Ehm, \"hi\", he \\ said" | awk '{$1="" ; print "\"" $_ "\"" }'
" "hi", he \ said"
(请勿更改回显,通常我从其中包含Ehm, "hi", he \ said
的文件读取).
(do not change the echo, normally I read from a file that has Ehm, "hi", he \ said
in it).
我想要
" \"hi\", he \\ said"
相反.我怎样才能做到这一点? awk中是否有一个功能可以做到这一点?
instead. How can I do this? Is there a function in awk that can do this?
推荐答案
这是您要寻找的吗?
$ 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"
这篇关于如何使用awk转义反斜杠和双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文