Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete all lines before a specific string from a number of files

Tags:

bash

shell

sed

I have n files, like:

file1:

1aaa
2eee

Test        XXX
Hanna
Lars 

file2:

1fff
2ddd
3zzz

Test        XXX
Mike
Charly

I want to remove all rows before "Test XXX" from all n files. The number of rows to delete varies between files.

My idea:

for file in 1 :n
do
pos=grep -n "Test XXX" file$file
sed -i "1:$pos-1 d" file$file >new$file
done
like image 224
Hans Avatar asked Sep 14 '11 13:09

Hans


People also ask

How do I delete a range of lines in Linux?

The sed command can remove the lines of any range. For this, we just have to enter 'minimum' and 'maximum' line numbers. In this example, we will remove the lines ranging from 4 to 7 numbers. After removing these ranges of lines, our file will look like this.


2 Answers

This should work for you:

sed -i '1,/Test XXX/d' file1
sed -i '1,/Test XXX/d' file2

or simply

sed -i '1,/Test XXX/d' file*
like image 145
ztank1013 Avatar answered Oct 25 '22 05:10

ztank1013


This will work for your examples and even if the matched pattern is on the very first line:

sed -n -E -e '/Text XXX/,$ p' input.txt | sed '1 d'

For example if you input is simply

Test        XXX
Mike
Charly

This will give you

Mike
Charly

If you want to keep the first match Test XXX then just use:

sed -n -E -e '/Text XXX/,$ p' input.txt
like image 29
Alec Jacobson Avatar answered Oct 25 '22 03:10

Alec Jacobson