简体   繁体   中英

How to print line numbers changed by sed / awk

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

I just need a simple text replace, no regex is needed:

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

I will need it for a bash script.

Thanks in advance!

You could swing it a couple ways:

vim

Using a text editor you can interactively replace patterns, the editor will prompt before every substitution. So you can choose y or n for each case.

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

diff

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

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

or

$ diff -y file tmpfile

Play around with man diff for other cool visualizations.

Then when you're sure it's okay, do:

$ mv tmpfile file

It's an extension to POSIX, but cat -n file.txt | ... cat -n file.txt | ... is an elegant solution to adding line numbers.

You could try creating the updated file with sed , run both the original and updated files through cat -n to temp. files, and then diff -q the both of the latter.

Another approach, something along the lines of cat -n original.txt | sed -n 's/[ 0-9]{7} .*pattern.*/replacement/gp cat -n original.txt | sed -n 's/[ 0-9]{7} .*pattern.*/replacement/gp . You would have to run the replace twice, but by the time you have numbered and diff 'd original and updated files then the only plus is diff could be considered more textbook technique possibly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM