如何在文件中替换sed脚本?

时间:2013-07-17 03:50:31

标签: shell sed

#!/bin/sed -f
s/","/|/g;                  # global change of "," to bar
# do some more stuff
#s/|/","/g;                  # global change of bar back to ","
#---end of script---

以上脚本从CSV中删除第二个字段,并清除引号等。我没有包含大部分脚本,因为它与问题无关。

脚本保存在文件fix.sh中。

我可以在这样的文件上运行它:

$ ./fix.sh <myfile.txt >outputfile.txt

效果很好。

但我希望它在文件中替换。这不起作用:

$ ./fix.sh <myfile.txt >myfile.txt

导致空myfile.txt

这也不起作用:

$ ./fix.sh myfile.txt

我尝试在sed bash脚本上找到一些文档,但找不到任何可以帮助我的内容。

我确定答案很简单,我找不到它。谢谢你的帮助。

编辑:我应该提到这是在CentOS 6机器上运行的。

完整脚本如下。它的总体结果是删除字段#2和条带引号。

#!/bin/sed -nf
# adapted from http://www.linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq4_005.html
s/","/|/g;                  # global change of "," to bar
s/^"//;
s/"$//;
s/^\([^|]*\)|[^|]*|/\1|/;   # delete 2nd field contents
s/||/|/;                        # change || to |
s/ //g;                         # remove spaces
s/|/,/g;
#s/|/","/g;                  # global change of bar back to ","
#---end of script---

1 个答案:

答案 0 :(得分:2)

如果您的sed支持-i选项,那么您可以像这样运行脚本:

./fix.sh -i myfile.txt
-i的{​​p} sed选项执行文件内替换。

如果您的sed版本不支持-i选项,那么您可以执行以下操作,这与-i幕后操作完全相同:

./fix.sh myfile.txt > temp && mv temp myfile.txt

为什么重定向到同一个文件不起作用?

原因是重定向打开文件进行写入并最终清除任何现有内容。 sed然后尝试读取这个空文件,什么都不做。然后关闭该文件,然后您将获得一个空文件。

相关问题