Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Linux中从多个文件中删除文本行_Linux_Unix_Command Line - Fatal编程技术网

在Linux中从多个文件中删除文本行

在Linux中从多个文件中删除文本行,linux,unix,command-line,Linux,Unix,Command Line,有没有一种简单的方法可以在命令行中从一个充满文本文档的文件夹中删除同一行文本?我为此编写了一个Perl脚本: #!/usr/bin/perl use IO::Handle; my $pat = shift(@ARGV) or die("Usage: $0 pattern files\n"); die("Usage $0 pattern files\n") unless @ARGV; foreach my $file (@ARGV) { my $io = new IO

有没有一种简单的方法可以在命令行中从一个充满文本文档的文件夹中删除同一行文本?

我为此编写了一个Perl脚本:

#!/usr/bin/perl

use IO::Handle;

my $pat = shift(@ARGV) or
    die("Usage: $0 pattern files\n");
die("Usage $0 pattern files\n")
    unless @ARGV;

foreach my $file (@ARGV) {
    my $io = new IO::Handle;
    open($io, $file) or
        die("Cannot read $file: $!\n");
    my @file = <$io>;
    close($io);
    foreach my $line (@file) {
        if($line =~ /$pat/o) {
            $line = '';
            $found = 1;
            last;
        }
    }
    if($found) {
        open($io, ">$file") or
            die("Cannot write $file: $!\n");
        print $io @file;
        close($io);
    }
}

如果您的sed版本允许使用
-i.bak
标志(就地编辑):

如果不是,只需将其放入bash循环中:

for file in *.txt
do
    sed '/line of text/d' "$file" > "$file".new_file.txt
done
以grep-v为例:

for thefile in *.txt ; do
   grep -v "text to remove" $thefile > $thefile.$$.tmp
   mv $thefile.$$.tmp $thefile
done
Grep-v显示除匹配行以外的所有行,它们进入临时文件,然后tmpfile移回旧文件名

perl -ni -e 'print if not /mystring/' *
这告诉perl在文件(-n)上循环,就地编辑(-i),如果行与正则表达式不匹配,则打印该行

有点相关,这里有一个对多个文件执行替换的简便方法

perl -pi -e 's/something/other/' *

要查找模式并删除模式,可以使用下面包含模式的行命令

find . -name "*" -type f | xargs sed -i -e '/<PATTERN>/d'

注意:在选择模式之前要小心,因为它将递归删除当前目录层次结构中所有文件中的行:)

+1(对于
-i.bak
gsed fu)。你的
for循环
可能需要一个
mv$file.new\u file.txt$file
来匹配它。@罗伯特,如果你错过了正确的sed,你仍然可以这样做:
perl-pi.bak-e的|文本行| | g'\*
留下一个空行而不是删除该行,对吗?
$(ls*.txt)
很愚蠢(分叉额外进程,无法处理文件名中的空格).try
for file in*.txt
instead如果文件夹有子目录,我会失败。
sed-i'/foo/d'*.
工作正常。因此:perl和sed都是传统的NFA引擎,因此理论上它们的性能应该不会有太大差异,但实际上perl应用了大量优化,使其性能更好orm在普通情况下很好。如果文件夹路径或文件名包含空格,则此操作不起作用。谢谢你,Sitesh..它使我从今天的工作时间中解脱出来。
perl -pi -e 's/something/other/' *
find . -name "*" -type f | xargs sed -i -e '/<PATTERN>/d'
find . -name "*.xml" -type f | xargs sed -i -e '/sleep/d'