How to print line numbers modified by sed / awk

Is it possible to print line number and line content that have been modified by sed?

I just need to just replace the text, no regex needed:

sed -i "s:replace_me:replaced:" test.c

      

I will need this for a bash script.

Thanks in advance!

+3


source to share


2 answers


You can download it in several ways:

VIM

Using a text editor, you can interactively replace templates, the editor will prompt before each substitution. Thus, you can choose y

or n

for each occasion.

$ vim file
:%s/pattern/replace/gc

      

diff

Using diff you can easily compare the two files and see the changes:



$ sed 's/pattern/replace/g' file > tmpfile
$ diff -u file tmpfile

      

or

$ diff -y file tmpfile

      

Play with man diff

for other interesting visualizations.

Then, when you are sure everything is ok, do:

$ mv tmpfile file

      

+2


source


This is a POSIX extension, but cat -n file.txt | ...

an elegant solution for adding line numbers.

You can try to create an updated file with sed

, run both original and updated files with cat -n

pre temp. files and then diff -q

both of them.



Another approach, something like cat -n original.txt | sed -n 's/[ 0-9]{7} .*pattern.*/replacement/gp

. You will have to run the replace twice, but by the time you have numbered and diff

'd the original and updated files, then the only plus diff

can be considered a more educational method.

0


source







All Articles