bash 如何从多个文件中删除特定字符串之前的所有行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7416921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:47:05  来源:igfitidea点击:

How can I delete all lines before a specific string from a number of files

bashshellsed

提问by Hans

I have n files, like:

我有 n 个文件,例如:

file1:

文件 1:

1aaa
2eee

Test        XXX
Hanna
Lars 

file2:

文件2:

1fff
2ddd
3zzz

Test        XXX
Mike
Charly

I want to remove all rows before "Test XXX" from all n files. The number of rows to delete varies between files.

我想从所有 n 个文件中删除“Test XXX”之前的所有行。要删除的行数因文件而异。

My idea:

我的点子:

for file in 1 :n
do
pos=grep -n "Test XXX" file$file
sed -i "1:$pos-1 d" file$file >new$file
done

回答by ztank1013

This should work for you:

这应该适合你:

sed -i '1,/Test XXX/d' file1
sed -i '1,/Test XXX/d' file2

or simply

或者干脆

sed -i '1,/Test XXX/d' file*

回答by Alec Jacobson

This will work for your examples and even if the matched pattern is on the very first line:

这将适用于您的示例,即使匹配的模式在第一行:

sed -n -E -e '/Text XXX/,$ p' input.txt | sed '1 d'

For example if you input is simply

例如,如果您输入只是

Test        XXX
Mike
Charly

This will give you

这会给你

Mike
Charly

If you want to keep the first match Test XXXthen just use:

如果你想保持第一场比赛,Test XXX那么只需使用:

sed -n -E -e '/Text XXX/,$ p' input.txt

回答by Tim Harper

cat <<-EOF > file1.txt
1aaa
2eee

Test        XXX
Hanna
Lars
EOF

cat file1.txt | sed -e '/Test *XXX/p' -e '0,/Test *XXX/d'

Output:

输出:

Test        XXX
Hanna
Lars

Explanation:

解释:

  • -e '/Test *XXX/p'duplicates the line matching /Test *XXX/
  • -e '0,/Test *XXX/d'deletes from line 0 to the first line matching /Test *XXX/
  • -e '/Test *XXX/p'重复行匹配 /Test *XXX/
  • -e '0,/Test *XXX/d'从第 0 行删除到匹配的第一行 /Test *XXX/

By duplicating the line, then removing the first one, we effectively retain the matched line, successfully deleting all lines BEFORE Test XXX

通过复制该行,然后删除第一行,我们有效地保留了匹配的行,成功删除了所有行 BEFORE Test XXX

Note: this will not work as expected if there are multiple Test XXXlines.

注意:如果有多Test XXX行,这将不会按预期工作。

回答by bash-o-logist

You can do it with bash( eg for 1 file)

您可以使用bash(例如,对于 1 个文件)

t=0
while read -r line
do
    [[ $line =~ Test.*XXX ]] && t="1"
    case "$t" in
     1) echo "$line";;
    esac
done < file > tempo && mv tempo file

Use a forloop as necessary to go through all the files

for根据需要使用循环来遍历所有文件