对目录中的所有文件运行,分别对待每一个,使用AWK [英] Run on all files in a directory, treating each separately, using AWK
问题描述
我想运行在一个目录下的每个文件的awk脚本,但AWK命令必须只在该文件中运行 - 也就是说,它确定的RS之间的搜索和返回什么是应该,但我需要它停止,当它到达一个文件的末尾,以及在下一文件的开头重新开始。
I want to run an AWK script on each file in a directory, but the AWK command must run only within that file - that is, it searches between a defined RS and returns what it is supposed to, but I need it to stop when it reaches the end of one file, and begin again at the start of the next file.
我有这个运行的单独对每个文件如下:
I have this running which works on each file individually:
awk '!/value1|value2/ && NF {print FILENAME " - " RS,$1}' RS="value" file1 > result.txt
但输出不正确的,也就是说,使用在一个目录其应用到每个文件时
But the output isn't correct, say, when applying it to each file in a directory using
find . -type f | awk ... file1 > result.txt
我将如何得到它在每个文件单独看,但结果追加到同一个文件?我不知道很遗憾。我想这是通过将每个文件到一个变量有AWK看看那个,但我不知道该怎么做。
How would I get it to look at each file individually, but append the results into the same file? I have no idea unfortunately. I guess it's by adding each file into a variable and having AWK look at that, but I am not sure how to do it.
interface Vlan3990
ip address 172.17.226.23 255.255.255.254
文件文件2:
version 12.2
ip tacacs source-interface Loopback99
ip vrf test
description xx
interface Loopback99
description Management Loopback
interface Loopback100
shutdown
输出
find . -type f | xargs awk '!/description|shutdown/ && NF {print FILENAME " - " RS,$1}' RS="interface" | more
./file1 - interface Vlan3990
./file2 - interface version
我不知道那里的输出接口版本'从...
I am not sure where the output 'interface version' is coming from...
推荐答案
试试这个,给你2张贴输入文件:
Try this, given your 2 posted input files:
$ gawk '
function prtName() {
if (name)
print FILENAME, name
name=""
}
/^interface/ { prtName(); name=$0 }
/^ (description|shutdown)/ { name="" }
ENDFILE { prtName() }
' file1 file2
file1 interface Vlan3990
这就是你想要的?请注意,这是gawk的特异性(礼貌 ENDFILE
),我认为是好的,因为你张贴的样本命令也呆子,具体的,但如果这是一个问题,只需添加一个测试FNR == 1和变革ENDFILE来结束:
Is that what you're looking for? Note that it's gawk-specific (courtesy of ENDFILE
) which I assume is fine since the sample command you posted is also gawk-specific but if that's an issue just add a test for FNR==1 and change ENDFILE to END:
$ awk '
function prtName() {
if (name)
print filename, name
name=""
}
FNR==1 { prtName(); filename=FILENAME }
/^interface/ { prtName(); name=$0 }
/^ (description|shutdown)/ { name="" }
END { prtName() }
' file1 file2
file1 interface Vlan3990
这篇关于对目录中的所有文件运行,分别对待每一个,使用AWK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!