gpt4 book ai didi

shell - sed:同时就地替换,并打印出更改的行?

转载 作者:行者123 更新时间:2023-12-04 11:28:57 24 4
gpt4 key购买 nike

说我有这个文件:

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

假设我想用 'TWO' 替换所有单词 'two',在文件 test.txt 中就地内联.

现在,我所做的通常是构建一个“预览”(使用 -n 不打印行,然后使用 /p - 仅打印匹配的行):
$ sed -n 's/two/TWO/gp' test.txt 
line TWO word
line one TWO word

...然后我通常执行实际的就地替换(使用 -i ,不使用 /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要在文件中就地更改行,并将更改的行从单个命令行打印到标准输出?

最佳答案

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

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

在 BSD 系统(包括 Mac OS X)上, sed关于何时可以将 Action 组合到一行中的规则有点古怪,我不得不使用:
sed -i '/two/{s/two/TWO/g; w /dev/stdout
}' test.txt

关于shell - sed:同时就地替换,并打印出更改的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8236794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com