[英]Is there any way to remove the first occurence of pattern by sed?
This is a test file: 这是一个测试文件:
xxx
hello
hello
others
I want to use sed: 我想使用sed:
sed -i '/hello/d' the_test_file
This will remove all lines contain "hello", so how to just remove the first line contains "hello"? 这将删除所有包含“ hello”的行,那么如何只删除包含“ hello”的第一行?
I think sed cant do it, but with perl i can. 我认为sed无法做到这一点,但是使用perl可以。 it's like: 就像是:
perl -00 -pe "s/hello//" the_test_file > /tmp/file && mv /tmp/file the_test_file
Show the original content of the file. 显示文件的原始内容。
cat the_test_file
1
2
3
popo
hello 1
hello 2
others
Show the result after running the sed command 运行sed命令后显示结果
sed -e '0,/^hello/{//d;}' the_test_file
1
2
3
popo
hello 2
others
To finally answer your question 最后回答你的问题
NOTE: thanks to jaypal 注意:感谢jaypal
sed -i"bak" -e '0,/^hello/{//d;}' the_test_file
To remove the first hello 删除第一个问候
sed -e "/hello/ N;n;d;" the_test_file
To remove the second hello 删除第二个问候
sed -e "/hello/ N;n;n;d;" the_test_file
If there are more than 2 lines of hello consecutively, and want to retain the first hello and delete the rest 如果连续有两行以上的问候,并且想要保留第一个问候并删除其余的
sed -e ":loop" -e "/hello/ N; s/\(hello.*\)\n\(hello.*\)/\1/" -e "t loop" the_test_file
If there are more than 2 lines of hello consecutively, and want to retain the last hello only 如果连续有两行以上的问候,并且只想保留最后一个问候
sed -e ":loop" -e "/hello/ N; s/\(hello.*\)\n\(hello.*\)/\2/" -e "t loop" the_test_file
the_test_file the_test_file
xxx
hello1
hello2
hello3
others
awk
solution: awk
解决方案:
$ cat file
something
hello 1
else
hello 2
others
hello 3
$ awk '/hello/ && ++c==1{next}1' file
something
else
hello 2
others
hello 3
This does the trick (but doesn't generalize easily): 这可以解决问题(但不能轻易推广):
$ sed -e '1,/hello/p' -e '1,/hello/d' -e '/hello/d' <<!
> xxx
> hello
> hello
> others
!
xxx
hello
others
$
The logic is to print the lines from line 1 to the first line containing 'hello'; 逻辑是打印从第1行到包含'hello'的第一行的行; then delete those lines (so the automatic print does not happen); 然后删除这些行(这样就不会自动打印); thereafter, simply delete the lines matching 'hello'. 之后,只需删除与“ hello”匹配的行即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.