Why reading and writing the same file through I/O redirection results in an empty file in Unix?

前端 未结 4 1732
抹茶落季
抹茶落季 2020-12-11 04:16

If I redirect output of a command to same file it reads from, its contents is erased.

sed \'s/abd/def/g\' a.txt > a.txt

Can anyone expla

4条回答
  •  悲&欢浪女
    2020-12-11 05:13

    You need to use the -i option to edit the file in place:

    sed -i .bck 's/abd/def/g' a.txt

    EDIT: as noted by neil, the redirection first opens the file for writing thus clears it.

    EDIT2: it might be interesting for some reader

    On OSX, if you want to use -i with an empty extension to prevent the creation of a backup file, you need to use the -eswitch as well otherwise it fails to parse the arguments correctly:

    sed -i -e 's/abc/def/g' a.txt

提交回复
热议问题