gpt4 book ai didi

shell - sed 命令创建随机命名的文件

转载 作者:行者123 更新时间:2023-12-03 23:46:36 32 4
gpt4 key购买 nike

我最近编写了一个执行 sed 命令的脚本,将名为“test.txt”的文件中所有出现的“string1”替换为“string2”。

它看起来像这样:

sed -i 's/string1/string2/g' test.txt

问题是,“string1”不一定存在于 test.txt 中。

我注意到在执行了一堆这些 sed 命令后,我得到了许多空文件,留在目录中,名称如下所示:

“sed4l4DpD”

有谁知道这可能是为什么,我该如何纠正?

最佳答案

-i是新/输出文件的后缀。另外,您需要-e为命令。
以下是您如何使用它:

sed -i '2' -e 's/string1/string2/g' test.txt

这将创建一个名为 test.txt2 的文件那是 test.txt的备份

要替换文件(而不是创建新副本 - 称为“就地”替换),请更改 -i值到 '' (即空白):
sed -i '' -e 's/string1/string2/g' test.txt

编辑二

这是 Mac (Snow Leopard) 的实际命令行输出,显示我修改后的答案(从 -i 和后缀之间删除了空格)是正确的。
注意:在 Linux 服务器上,它之间不能有空格 -i和后缀。
> echo "this is a test" > test.txt
> cat test.txt
this is a test
> sed -i '2' -e 's/a/a good/' test.txt
> ls test*
test.txt test.txt2
> cat test.txt
this is a good test
> cat test.txt2
this is a test
> sed -i '' -e 's/a/a really/' test.txt
> ls test*
test.txt test.txt2
> cat test.txt
this is a really good test

关于shell - sed 命令创建随机命名的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7733922/

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