如何使用变量包括AWK特殊符号? [英] How to use variable including special symbol in awk?
问题描述
有关我的情况下,如果某个模式被发现是一条线的一个文件中的第二个字段,然后我需要打印前两个字段。它应该能够处理的情况下像反斜线特殊符号。
For my case, if a certain pattern is found as the second field of one line in a file, then I need print the first two fields. And it should be able to handle case with special symbol like backslash.
,那么awk将解析\\\\为\\然后匹配字段2
My solution is first using sed to replace \ with \\, then pass the new variable to awk, then awk will parse \\ as \ then match the field 2.
escaped_str=$( echo "$pattern" | sed 's/\\/\\\\/g')
input | awk -v awk_escaped_str="$escaped_str" '$2==awk_escaped_str { $0=$1 " " $2 " "}; { print } '
虽然这看起来过于复杂,并且无法处理各种情况。
While this seems too complicated, and cannot handle various case.
有没有哪个更简单,可以覆盖所有其它特殊符号?一个更好的办法
Is there a better way which is more simpler and could cover all other special symbol?
推荐答案
通过一个shell变量没有反斜杠是间preTED到awk的方式是把它传中,ARG列表,而不是填充之外的一个awk变量脚本:
The way to pass a shell variable to awk without backslashes being interpreted is to pass it in the arg list instead of populating an awk variable outside of the script:
$ shellvar='a\tb'
$ awk -v awkvar="$shellvar" 'BEGIN{ printf "<%s>\n",awkvar }'
<a b>
$ awk 'BEGIN{ awkvar=ARGV[1]; ARGV[1]=""; printf "<%s>\n",awkvar }' "$shellvar"
<a\tb>
,然后你可以使用指数()
或 ==
搜索文件为一个字符串:
and then you can search a file for it as a string using index()
or ==
:
$ cat file
a b
a\tb
$ awk 'BEGIN{ awkvar=ARGV[1]; ARGV[1]="" } index($0,awkvar)' "$shellvar" file
a\tb
$ awk 'BEGIN{ awkvar=ARGV[1]; ARGV[1]="" } $0 == awkvar' "$shellvar" file
a\tb
您需要设置 ARGV [1] =
填充awk的变量,以避免shell变量的值也被视为一个文件名之后。不同于传递一个变量的任何其他方式,在一个变量以这种方式使用的所有字符都没有特殊的含义从字面上对待。
You need to set ARGV[1]=""
after populating the awk variable to avoid the shell variable value also being treated as a file name. Unlike any other way of passing in a variable, ALL characters used in a variable this way are treated literally with no "special" meaning.
这篇关于如何使用变量包括AWK特殊符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!