[ILUGC] Re: How to insert a new line above 2 lines (above the pattern match)

  • From: Abdun Nihaal <nihaal.an@xxxxxxxxx>
  • To: ilugc@xxxxxxxxxxxxx
  • Date: Fri, 4 Sep 2020 22:40:32 +0530

On Fri, Sep 04, 2020 at 06:31:41PM +0530, Baskar Selvaraj wrote:

Hi all,
I have been searching for a solution for inserting a new line above the
pattern match (2 lines above the pattern)

Following is one solution. There could be simpler methods.
Assuming "file" is the name of the file

for line in `cat file | grep -e '-->' -n | cut -d":" -f1 | sort -r`;
do
sed -e "$(($line-1))s/\(.*\)/\n\1/" -i file;
done

This just finds the line numbers and inserts a newline in the previous
line. Note that the insertions are done in reverse line number order
because if done in ascending order the subsequent line numbers will
change.

Regards,
Abdun Nihaal
---
Mailing List Guidelines: https://ilugc.in/mailing-list-guidelines
Web: http://ilugc.in/
Internet Relay Chat: #ilugc on irc.freenode.net

Other related posts: