regex - 使用 Perl 匹配一些行并删除它们

标签 regex perl

问题:

许多文件 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/

相关文章:

Ruby 的 String#gsub、unicode 和非单词字符

mysql - 加速查询 : ORDER BY with LIMIT (indexing? )

php - 为什么 PHP 中的字符串连接使用句号 "."而不是加号 "+"?

perl - 在同一包中的文件之间使用常量

xml - 使用 XML::Simple 时如何删除魔数(Magic Number)?

javascript - String.prototype.replace() 删除破折号和下划线

regex -/m 修饰符的 perl 正则表达式意外行为

regex - 更改第一个括号中后跟第三个/方括号的文本

python - 如何使用正则表达式在 Python 中搜索字符串中的重复词?

perl - 从排序 block 返回给出 "Use of uninitialized value in sort"警告,但只有显式返回