Sed: simultaneous in-place replacement and printout of modified lines?

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 me say that I want to replace all the words "two" with "TWO", inline in place in the file test.txt .

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

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

... and then I usually do 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 both to change lines in place in a file, and to print changed lines in stdout from one command line?

+6
source share
1 answer

On Linux, you can get away with:

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

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

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

Source: https://habr.com/ru/post/902169/


All Articles