[英]Passing a shell variable into an awk command
I have a loop that processes a bunch of files within a dir. 我有一个循环,可以处理目录中的一堆文件。 I would like to input the filename into the file it processes, but I'm getting an error.
我想将文件名输入到要处理的文件中,但是出现错误。 It works perfectly with the
myvar
syntax but I need that for obvious reasons. 它与
myvar
语法完美配合,但是出于明显的原因,我需要它。
awk: cmd. line:1: RS=
awk: cmd. line:1: ^ unexpected newline or end of string
for filename in $files
do
awk -v "myvar=${filename}"
RS= '/-- Ticket/{++i; print "PROMPT myvar Line ",
i ORS $0 ORS; i+=split($0, a, /\n/)+1}' ${filename}.txt
done
Couple of issues here, use the -v
syntax for each of the variables that you are trying to pass to awk
, 这里有几个问题,对于要传递给
awk
每个变量,都使用-v
语法,
awk -v myvar="${filename}" -v RS= '/-- Ticket/{++i; print "PROMPT " myvar " Line ", i ORS $0 ORS; i+=split($0, a, /\n/)+1}' ${filename}.txt
# ^^^ variable1 ^^^^^ variable2 --> using separate -v for each
should be right approach. 应该是正确的方法。
For a shell variable import to awk
do it as in my example above, not as "myvar=${filename}"
but just myvar="${filename}"
对于要导入到
awk
的shell变量,请按照上面的示例进行操作,而不是"myvar=${filename}"
而只需myvar="${filename}"
If you could avoid a batch loop, it's better (performance mainly for subshell fork, ...) 如果可以避免批处理循环,那就更好了(性能主要用于subshell fork,...)
# assume TXT_files is the list of $files with .txt extension (not purpose of this OP)
awk RS='' '
/-- Ticket/{
# get the file name without extension
myvar = FILENAME;sub( /\.txt$/,"",myvar)
print "PROMPT " myvar " Line " ++i ORS $0 ORS
i += split( $0, a, /\n/) + 1
}
' ${TXT_files}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.