不要那样做,只使用 awk,例如:
awk -F'|' '
NR==FNR { if (NR==1) var = $2$4; next }
{ gsub(/<remote>.*<\/remote>/,"<remote> http://blabla/" var " </remote>"); print }
' file file2.xml > tmp && mv tmp file2.xml
使用 GNU awk,您可以提高效率,但除非您的第一个文件很大,否则不会产生明显的影响:
awk -F'|' '
NR==FNR { var = $2$4; nextfile }
{ gsub(/<remote>.*<\/remote>/,"<remote> http://blabla/" var " </remote>"); print }
' file file2.xml > tmp && mv tmp file2.xml
wrt 我在其他人的帖子中发表的评论,这就是为什么您应该使用 -v var=val 而不是在 awk args 列表中填充变量,除非您需要这样做来更改文件之间的初始值(GNU awk 不需要这样做)开始文件):
这是一个脚本,用于将存储在 3 个文件中的值添加到某个初始种子值并打印每个文件和所有文件的结果(种子只添加到总数中一次)。文件 2 为空:
$ cat file1
3
6
$ cat file2
$ cat file3
2
5
$ cat tst.awk
BEGIN {
print "seed value =", seed
for (i=1; i<ARGC; i++)
subtotal[ARGV[i]] = seed
total = seed
}
{
subtotal[FILENAME] += $0
total += $0
}
END {
for (filename in subtotal)
print "File", filename, "subtotal =", subtotal[filename]
print "total =", total
}
$
$ awk -v seed=7 -f tst.awk file1 file2 file3
seed value = 7
File file1 subtotal = 16
File file2 subtotal = 7
File file3 subtotal = 14
total = 23
一切都说得通吧?现在让我们将“种子”的设置移动到参数列表中:
$ awk -f tst.awk seed=7 file1 file2 file3
seed value =
File file1 subtotal = 9
File file2 subtotal =
File file3 subtotal = 7
File seed=7 subtotal =
total = 16
请注意,第一次打印时缺少种子值,小计和总计错误,并且输出试图打印名为“seed=7”的文件的值。
一旦你确切地知道你在用 awk 做什么,这一切都是可以解释和可预测的,但我敢打赌,这对新手来说相当莫名其妙,所以恕我直言,在 arg 列表中填充变量不应该是我们建议人们默认初始化变量的方式,因为它的语义远没有-v variable=value那么直观。