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.
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
$ 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With