Delete lines that come after a line with a specific pattern in Shell
This is very trivial with text processing utilities. For example, using sed
:
sed '1,/pattern/!d' file
Meaning, match every line from the first one to the one with pattern
and delete all the non-matched lines. So, replace pattern
with your pattern. If it contains /
, you need to escape those characters. For example, if the pattern is pattern-with/character
:
sed '1,/pattern-with\/character/!d' file
To actually edit files (rather than print the edited stream to stdout), you can use the -i
flag:
sed -i '1,/pattern/!d' file
You can make a backup of the original file by adding an extension for the old file to -i
. Take care here - you must not include a space before the extension.
sed -i.backup '1,/pattern/!d' file
sed
takes multiple filename arguments. For example, to act on all the non-hidden files in the current directory you could use:
sed -i '1,/pattern/!d' *
Another solution, using awk:
awk '/specific-pattern/{stop=1} stop==0{print}' < input_file >> output_file
While the variable stop
is 0 (which is is, by default), awk will print the current line. However, if the current line matches the regular expression /specific-pattern/, then stop
will be set to 1. This makes stop==0
untrue, so awk will no longer execute the print
statement.
Input is read from input_file and appended to output_file.
If you want to keep the line with the pattern, reverse the two parts of the awk script.
Thank you @Zanna
I found this solution :
for ((i=1;i < $count+1 ;i++))
sed -n '/PATTERN/q;p' $i.txt > file_out$i.txt
Thank you