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

Rob*_*ert 50 unix linux command-line

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

enn*_*ler 51

如果您的sed版本允许-i.bak标记(在适当的位置编辑):

sed -i.bak '/line of text/d' * 
Run Code Online (Sandbox Code Playgroud)

如果没有,只需将其放入bash循环:

for file in *.txt
do
    sed '/line of text/d' "$file" > "$file".new_file.txt
done
Run Code Online (Sandbox Code Playgroud)

  • `$(ls*.txt)`是愚蠢的(分叉额外进程,无法处理文件名中的空格).尝试`for file in*.txt` (4认同)

Sit*_*esh 24

可以使用查找a pattern和删除the line containing the pattern下面的命令

find . -name "*" -type f | xargs sed -i -e '/<PATTERN>/d'
Run Code Online (Sandbox Code Playgroud)

示例:如果要删除sleep所有xml文件中包含单词的行

find . -name "*.xml" -type f | xargs sed -i -e '/sleep/d'
Run Code Online (Sandbox Code Playgroud)

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


Ry4*_*ase 6

考虑 grep -v:

for thefile in *.txt ; do
   grep -v "text to remove" $thefile > $thefile.$$.tmp
   mv $thefile.$$.tmp $thefile
done
Run Code Online (Sandbox Code Playgroud)

grep -v 显示除匹配的行之外的所有行,它们进入临时文件,然后 tmpfile 移回旧文件名。


Mar*_*son 6

perl -ni -e 'print if not /mystring/' *
Run Code Online (Sandbox Code Playgroud)

这告诉 perl 循环遍历您的文件 (-n),就地编辑 (-i),并在与您的正则表达式不匹配时打印该行。

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

perl -pi -e 's/something/other/' *
Run Code Online (Sandbox Code Playgroud)