Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

regex - Print the line matching 'pattern' string, excluding the 'pattern'

I have the following lines in a text file 'file.txt'

String1 ABCDEFGHIJKL
String2 DCEGIJKLQMAB

I want to print the characters corresponding to 'String1' in another text file 'text.txt' like this

ABCDEFGHIJKL

Here, I don't want to use any line numbers. Any suggestions using 'sed' command?. I tried with between 'string 1' and 'string 2', but couldn't obtain command excluding 'string1'. This following code for excluding only 'string2'.

sed -n '/^string1/,/^string2/{p;/^string2/q}' file.txt | sed '$d' > text.txt

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use GNU grep:

grep -Po 'String1s+K.*' in_file

Here, grep uses the following options:
-P : Use Perl regexes.
-o : Print the matches only (1 match per line), not the entire lines.

K : Cause the regex engine to "keep" everything it had matched prior to the K and not include it in the match. Specifically, ignore the preceding part of the regex when printing the match.

SEE ALSO:
grep manual
perlre - Perl regular expressions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...