Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all lines before first occurrence of specific string in file

Tags:

bash

sed

awk

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.

like image 448
mtveezy Avatar asked Mar 13 '16 02:03

mtveezy


2 Answers

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
like image 177
l'L'l Avatar answered Oct 22 '22 16:10

l'L'l


$ sed -n '/somestring/,$p' infile
somestring
bats
car
somestring
bats
car
somestring
bats
car

The command suppresses printing with -n, and then for the address range /somestring/,$, i.e., from somestring to the last line, executes the p command to print the line.

like image 22
Benjamin W. Avatar answered Oct 22 '22 17:10

Benjamin W.