sed:同时就地替换,并打印出更改的行? [英] sed: simultanous in-place replacement, and printout of changed lines?

查看:90
本文介绍了sed:同时就地替换,并打印出更改的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个文件:

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

假设我想将文件 test.txt<中的所有单词two"替换为TWO",inline 就地/代码>.

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

现在,我所做的通常是构建一个预览"(使用 -n 不打印行,然后使用 /p - 仅打印匹配的行):

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

... 然后我通常会执行实际的就地替换(使用 -i,不使用 /p):

... 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

有没有办法让 sed 在文件中就地更改行,从单个命令行将更改的行打印到标准输出?

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?

推荐答案

在 Linux 上,您可能能够逃脱:

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

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

在 BSD 系统(包括 Mac OS X)上,sed 对何时可以将操作组合到一行中的规则有点古怪,我不得不使用:

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

这篇关于sed:同时就地替换,并打印出更改的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆