Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

bash - Delete all lines before first occurrence of specific string in file

Basically I have a file like:

junk
morejunk
somestring
bats
car
somestring
bats
car
somestring
bats
car

and I want to remove all of the junk before the first occurrence of somestring so the file looks like

somestring
bats
car
somestring
bats
car
somestring
bats
car

I followed the advice from this question to use sed -i '0,/somestring/,d' file.txt but it deletes the line with the first occurrence of somestring, when I want to keep that line as the first line.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

With sed you could use:

sed -i '/somestring/,$!d' file

Explanation of replace expressions:

, matches lines starting from where the first address matches, and continues until the second match (inclusively).

$ matches the last line of the last file of input, or the last line of each file when the -i or -s options are specified.

! If the character follows an address range, then only lines which do not match the address range will be selected.

d Delete the pattern space; immediately start next cycle.

Result:

$ sed -i '/somestring/,$!d' file
somestring
bats
car
somestring
bats
car
somestring
bats
car

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...