Grep Command to Add End Line After Every Match

new line separator for each grep result sh script

grep "pattern" /path/to/file | awk '{print $0,"\n"}'

How to give a pattern for new line in grep?

grep patterns are matched against individual lines so there is no way for a pattern to match a newline found in the input.

However you can find empty lines like this:

grep '^$' file
grep '^[[:space:]]*$' file # include white spaces

How to show only next line after the matched one?

you can try with awk:

awk '/blah/{getline; print}' logfile

grep: show lines surrounding each match

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match.

grep -B 3 -A 2 foo README.txt

If you want the same number of lines before and after you can use -C num.

grep -C 3 foo README.txt

This will show 3 lines before and 3 lines after.

how to insert line break after a specific string?

With any sed that accepts \n as meaning "newline":

$ sed 's/S\./&\n/g' file
1900-01-01 00:00:00|1|S|S|S|S.
1900-01-01|S.
1900-01-01 00:00:00|1|S|S|S|S.
1900-01-01 00:00:00|1|S|S|S|S.

or in bash for $'\n' to get a newline char:

$ sed 's/S\./&\'$'\n''/g' file
1900-01-01 00:00:00|1|S|S|S|S.
1900-01-01|S.
1900-01-01 00:00:00|1|S|S|S|S.
1900-01-01 00:00:00|1|S|S|S|S.

or portably with any sed in any shell:

$ sed 's/S\./&\
/g' file
1900-01-01 00:00:00|1|S|S|S|S.
1900-01-01|S.
1900-01-01 00:00:00|1|S|S|S|S.
1900-01-01 00:00:00|1|S|S|S|S.

Note that the output will end in a blank line since the script adds a newline after every S. as requested. If you actually only want to add a newline after every S. mid-line then that'd be:

$ sed 's/\(S\.\)\(.\)/\1\n\2/g' file
1900-01-01 00:00:00|1|S|S|S|S.
1900-01-01|S.
1900-01-01 00:00:00|1|S|S|S|S.
1900-01-01 00:00:00|1|S|S|S|S.

How to add to the end of lines containing a pattern with sed or awk?

This works for me

sed '/^all:/ s/$/ anotherthing/' file

The first part is a pattern to find and the second part is an ordinary sed's substitution using $ for the end of a line.

If you want to change the file during the process, use -i option

sed -i '/^all:/ s/$/ anotherthing/' file

Or you can redirect it to another file

sed '/^all:/ s/$/ anotherthing/' file > output


Related Topics



Leave a reply



Submit