Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed: simultanous in-place replacement, and printout of changed lines?

Tags:

shell

sed

Say I have this file:

cat > test.txt <<EOF
line one word
line two word
line three word
line one two word
EOF

And let's say I want to replace all of the words 'two' with 'TWO', inline in-place in the file test.txt.

Now, what I do, is usually construct a "preview" (with -n don't print lines, and then with /p - print matched lines only):

$ sed -n 's/two/TWO/gp' test.txt 
line TWO word
line one TWO word

... and then I usually execute the actual in-place replacement (with -i, and without /p):

$ sed -i 's/two/TWO/g' test.txt
$ cat test.txt 
line one word
line TWO word
line three word
line one TWO word

Is there a way to get sed to both change lines in-place in a file, and print the changed lines to stdout, from a single command line?

like image 803
sdaau Avatar asked Nov 23 '11 02:11

sdaau


1 Answers

On Linux, you may be able to get away with:

sed -i '/two/{s/two/TWO/g; w /dev/stdout}' test.txt

On BSD systems (including Mac OS X), where the sed has slightly eccentric rules about when you can combine actions onto a single line, I had to use:

sed -i '/two/{s/two/TWO/g; w /dev/stdout
       }' test.txt
like image 141
Jonathan Leffler Avatar answered Sep 21 '22 18:09

Jonathan Leffler