Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo or preview text changed using sed -i

Tags:

sed

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

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

The problem is that this has tremendous power, and a complex regular expression could easily have unforeseen consequences.

Is there a simple way to do either:

1) Echo the changes made
2) Run sed in a preview mode, so that the potential changes can be previewed

like image 757
port5432 Avatar asked Oct 01 '14 06:10

port5432


People also ask

Does sed modify files?

There is a huge pool of commands available for Ubuntu and sed command utility is one of them; the sed command can be used to perform fundamental operations on text files like editing, deleting text inside a file.

Can you use regex in sed?

The sed command has longlist of supported operations that can be performed to ease the process of editing text files. It allows the users to apply the expressions that are usually used in programming languages; one of the core supported expressions is Regular Expression (regex).

Which is better sed or awk?

Both sed and awk allow processing streams of characters for tasks such as text transformation. The awk is more powerful and robust than sed. It is similar to a programming language.


1 Answers

Run in preview mode without the -i:

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

(The -e is not necessary; it just says the next argument is the sed script, or one part of the sed script.) This writes all the output to standard output. You'd probably pipe it through less (or more), or pass it through grep to see that the changed lines were those you expected. Or you might process one file at a time and run a difference:

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

Or …

like image 191
Jonathan Leffler Avatar answered Oct 02 '22 15:10

Jonathan Leffler