我的目标是仅当路径与文件中的路径匹配时才删除文件中的行
例如,我需要从/tmp/file文件中删除所有具有/etc/sysconfig路径的行
more /tmp/file
/etc/sysconfig/network-scripts/ifcfg-lo file1
/etc/sysconfig/network-scripts/ifcfg-lo file2
/etc/sysconfig/network-scripts/ifcfg-lo file3为了删除包含"/etc/sysconfig“的行,我编写了以下Perl代码(集成在我的bash脚本中的perl代码)
export FILE=/etc/sysconfig
perl -i -pe 's/\Q$ENV{FILE}\E// ' /tmp/file 但是在我运行perl代码之后,我得到了以下代码:(在适当的地方获得空行)
/network-scripts/ifcfg-lo file1
/network-scripts/ifcfg-lo file2
/network-scripts/ifcfg-lo file3第一个问题:
如何更改perl语法: perl -i -pe 's/\Q$ENV{FILE }\E//‘以便删除与所需路径(/etc/sysconfig)匹配的行?
第二个问题:
与第一个问题相同,但仅当路径与文件中的第一个字段匹配时才会删除行
示例:
/tmp/file在perl编辑之前:
file1 /etc/sysconfig/network-scripts/ifcfg-lo
/etc/sysconfig/network-scripts/ifcfg-lo file2
/etc/sysconfig/network-scripts/ifcfg-lo file3perl编辑后的/tmp/file:
file1 /etc/sysconfig/network-scripts/ifcfg-lo 发布于 2010-10-06 05:36:08
Perl是一种很好的方法。请使用-n开关,而不是-p。
perl -i -l -n -e'print unless /\Q$ENV{FILE}/' filename发布于 2010-10-06 05:34:02
s/pattern/otherpattern/不会删除整行;它只会更改子字符串。你需要完全改变你的程序来删除整行。在伪代码中,它将是:
while (read in a line)
{
if (doesn't match)
{
write the line back out unaltered.
}
}但是,在了解了continue和redo如何在循环中工作的基础上,它仍然可以重写为一行程序:perl -pe '$_ = <> and redo if /Q$ENV{FILE}\E/'
发布于 2010-10-06 05:39:47
mef@iwlappy:~$ cat /tmp/file
aaaa
/etc/sysconfig/network-scripts/ifcfg-lofile1
/etc/sysconfig/network-scripts/ifcfg-lofile2
/etc/sysconfig/network-scripts/ifcfg-lofile3
aaa
mef@iwlappy:~$ perl -i -pe 's/$ENV{FILE}\E.*//' /tmp/file
mef@iwlappy:~$ cat /tmp/file
aaaa
aaa您可以使用s/^$//进一步执行regexp来删除空行
https://stackoverflow.com/questions/3867867
复制相似问题