简体   繁体   English

删除多个以某个单词开头的文本文件中的行

[英]Remove Lines in Multiple Text Files that Begin with a Certain Word

I have hundreds of text files in one directory. 我在一个目录中有数百个文本文件。 For all files, I want to delete all the lines that begin with HETATM. 对于所有文件,我想删除所有以HETATM开头的行。 I would need a csh or bash code. 我需要一个csh或bash代码。

I would think you would use grep, but I'm not sure. 我认为您会使用grep,但不确定。

Use sed like this: 像这样使用sed

sed -i -e '/^HETATM/d' *.txt

to process all files in place. 处理所有文件。

-i means "in place". -i表示“就位”。

-e means to execute the command that follows. -e表示执行以下命令。

/^HETATM/ means "find lines starting with HETATM", and the following d means "delete". / ^ HETATM /表示“以HETATM开头的find行”,后面的d表示“删除”。

Make a backup first! 首先进行备份!

If you really want to do it with grep , you could do this: 如果您确实想使用grep ,则可以执行以下操作:

#!/bin/bash

for f in *.txt
do
   grep -v "^HETATM" "%f" > $$.tmp && mv $$.tmp "$f"
done

It makes a temporary file of the output from grep (in file $$.tmp ) and only overwrites your original file if the command executes successfully. 它会生成grep输出的临时文件(位于$$.tmp文件中),并且仅在命令成功执行时才覆盖原始文件。

使用grep-v选项获取所有不匹配的行:

grep -v '^HETATM' input.txt > output.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM