Echo text or preview changed with sed -i

Using sed , you can easily change text in multiple files, for example:

 sed -i 's/cashtestUS/cheque_usd/g' *.xml

      

The problem is that this has tremendous power, and a complex regex can easily have unintended consequences.

Is there an easy way to do this:

1) Modify the changes made 2) Run sed in preview mode so you can preview the preview changes.

+3


source to share


2 answers


Run in preview mode without -i

:

sed -e 's/cashtestUS/cheque_usd/g' *.xml

      

( -e

optional, it just says the next argument is a sed

script, or one part of a sed

script.) This writes all output to standard output. You will probably run it through less

(or more

) or pipe it through grep

to see if the changed lines were what you expected. Or, you can process one file at a time and do the difference:



for file in *.xml
do
    echo "$file"
    sed -e 's/cashtestUS/cheque_usd/g' "$file" | diff -u "$file" -
done

      

Or...

+9


source


sed has several "debug / display actions"

  • =

    display the current line number
  • l

    displays the current contents of the working buffer with $

    at the end of the contents
  • i

    and a

    can be used to display a trace likei \ Debug trace here

  • If no storage buffer is used, h;s/.*/Debug Trace here/;g

    useful and does not appear at the end of line processing, for example i

    ora



Example:

echo "line 1
and two" | sed ':a
=;h;s/.*/Before substitution/;g;l
s/..$/-/
=;l
t a'

      

+1


source







All Articles