使用sed查找包含两个不同字符串的行,并将这些行写入输出文件。

huangapple go评论48阅读模式
英文:

Find lines that contain two different strings and then write these lines into output file using sed

问题

The issue with your command is that the | character in the regular expression is being treated as a literal character rather than an OR operator. To find lines that contain both "clk_a" and "clk_b," you should use \| instead of | within the regular expression. Here's the corrected command:

sed -n '/clk_a.*clk_b\|clk_b.*clk_a/w OUTFILE' INFILE

This command should correctly find lines that contain both "clk_a" and "clk_b" and write them to the "OUTFILE."

英文:

I want to find lines that contain two different strings, then write these lines into an output file.
INFILE be like:

clk_a,start_point,end_point,clk_b,0.5
clk_b,start_point,end_point,clk_a,0.5
clk_a,start_point,end_point,clk_c,0.5
clk_a,start_point,end_point,clk_d,0.5

I use the following command to find the desired lines, but it doesn't work. What's wrong with my command?

sed -n '/clk_a.*clk_b|clk_b.*clk_a/w OUTFILE' INFILE

答案1

得分: 1

这可能适用于你(GNU sed):

sed -n '/start/,/end/w outFile' file

或者

sed -n '/first/!b;/second/!b;w outFile' file

第一种解决方案将写出所有位于 startend 之间的行,包括包含 startend 的行。

第二种解决方案将写出同时包含 firstsecond 的所有行。

注:如果模式在文件中多次出现,所有出现都将被输出。


第二种解决方案可以缩短:

sed -n '/first/!b;/second/w outFile' file

如果你想要匹配 firstsecond 以及 third

sed -n '/first\|second/!b;/third/w outFile' file

或者

sed -n '/first/ba;/second/!b;/third/!b;:a;w outFile' file

取决于你想放置括号的位置。

英文:

This might work for you (GNU sed):

sed -n '/start/,/end/w outFile' file

or

sed -n '/first/!b;/second/!b;w outFile' file

The first solution will write out all lines between start and end including the lines containing start and end.

The second solution will write out all lines containing both first
and second.

N.B. If the pattern occurs multiple times within the file all occurrences will be output.


The second solution could be shortened:

sed -n '/first/!b;/second/w outFile' file

If you were want first or second and third:

sed -n '/first\|second/!b;/third/w outFile' file

or

sed -n '/first/ba;/second/!b;/third/!b;:a;w outFile' file

depending on where you were to place parenthesis.

huangapple
  • 本文由 发表于 2023年6月15日 16:22:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定