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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With