Why a linux redirect truncates the file?

2019-02-26 07:43发布

I have a file called "test.txt" like that:

hello world

it is, just a 'hello world' string. If I use a perl regex:

perl -pe "s/hello/bye/g" test.txt

it says:

bye world

but if I try to redirect that file to itself:

perl -pe "s/hello/bye/g" test.txt > test.txt

the resulting file is empty. Why? And how can I 'filter' a regex over a file?

3条回答
在下西门庆
2楼-- · 2019-02-26 08:03

It opens the file for writing due to the redirect before the application gets a chance to read from it. Redirect to a temporary file instead, then rename it after.

查看更多
爷的心禁止访问
3楼-- · 2019-02-26 08:05

perl accepts the parameter -i for inplace. With this, you can process a file with a perl program and immediately have it written back.

查看更多
别忘想泡老子
4楼-- · 2019-02-26 08:16

The redirection takes place while your shell is parsing your command line. This happens before the actual command is executed, thus the file you redirect to is overwritten before you have the chance to read it.

查看更多
登录 后发表回答