问题:
许多文件 name.CFG 中包含一些错误行(大约 2700 个文件)。如果存在坏线,我需要将其删除。
坏行包含文件名减去 .CFG
坏线:
Title[nameofdevice:cpu]: nameofdevice CPU Usage Mhz
Target[nameofdevice:cpu]:
MaxBytes[nameofdevice:cpu]: 100
Options[nameofdevice:cpu]: gauge
WithPeak[nameofdevice:cpu]: wmy
YLegend[nameofdevice:cpu]: Percent
ShortLegend[nameofdevice:cpu]: %
Legend1[nameofdevice:cpu]: CPU % for 1
Legend2[nameofdevice:cpu]: CPU Max for 2
Legend3[nameofdevice:cpu]: Max CPU Mhz for 1
Legend4[nameofdevice:cpu]: Max CPU Mhz for 2
Title[nameofdevice:mem]: nameofdevice mem
Target[nameofdevice:mem]:
MaxBytes[nameofdevice:mem]: 100
Options[nameofdevice:mem]: gauge
WithPeak[nameofdevice:mem]: wmy
YLegend[nameofdevice:mem]: Percent
ShortLegend[nameofdevice:mem]: %
Legend1[nameofdevice:mem]: % Used
Legend2[nameofdevice:mem]: Max Used
Legend3[nameofdevice:mem]: Max
nameofdevice
是文件名减去 .CFG
我一直在寻找一种 Linux 方式来做到这一点,但似乎 Perl 会更灵活。我真正的问题是与文本完全匹配。我想拥有多行和变量对我来说是令人困惑的,但是一个小字符串你可以做查找和替换之类的事情。或者使用SED
。
我需要从所有文件中删除坏行。
最佳答案
这可以解决问题(尽管我相信有更有效的方法来做到这一点):
find -iname '*.cfg' -execdir perl -i -ne '$f = $ARGV =~ s#\./|\.cfg##gr; print if !m/\b\Q$f\E\b/;' {} \+
如果您使用的是 Windows,则需要为就地 (-i
) 功能提供备份文件名:
find -iname '*.cfg' -execdir perl -ibak -ne '$f = $ARGV =~ s#\./|\.cfg##gr; print if !m/\b\Q$f\E\b/;' {} \+ && find -iname '*.cfgbak' -delete
find -iname '*.cfg'
查找当前目录和所有子目录中的每个 .cfg
文件。
Perl 脚本是:
# there's an implied while(<>) because of the -n option
# which executes this script for each line
# $ARGV is the current file path, strip ./ and .cfg
$f = $ARGV =~ s#\./|\.cfg##gr;
# print the current line if it doesn't contain the current file name
# as a whole word
print if !m/\b\Q$f\E\b/;
关于regex - 使用 Perl 匹配一些行并删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28669277/