1

I'm messing around with sed for fun and have a little function I found that replaces a few characters:

sed 's/"p"$/0/;s/"e"/1/' sedtext.txt

Where sedtext.txt is as follows:

1, 2, 6, 7, "p" 
1, 6, 7, 2, "e" 

When I do the following I get the desired output:

sed 's/"p"$/0/;s/"e"/1/' sedtest.txt > sedtest2.txt 

But when I try to overwrite the input file with the output I get a blank file:

sed 's/"p"$/0/;s/"e"/1/' sedtest.txt > sedtest.txt 

Why is this the case?

  • 2
    No, shell redirections are set up before the commands run. – Stephen Kitt Mar 06 '17 at 15:59
  • 2
    No. The shell opens (and truncates) the file before even executing the command. sed just prints to stdout, which the shell pointed at a file. It reads here from the file that the shell already ate – Fox Mar 06 '17 at 16:01
  • sed 's/"p"$/0/;s/"e"/1/' sedtest.txt > sedtest2.txt && mv sedtest2.txt sedtest.txt – Philip Kirkbride Mar 06 '17 at 16:02
  • You are changing the file while being processed. Use -i for that:
    sed -i 's/"p"$/0/;s/"e"/1/' sedtext.txt
    
    – Philippos Mar 06 '17 at 16:03
  • 2
    The -i (in-place) switch of GNU sed does (almost) exactly your workaround – Fox Mar 06 '17 at 16:03
  • 1
    Look at specifically this answer: http://unix.stackexchange.com/questions/159513/what-are-the-shells-control-and-redirection-operators#answer-186126 – Oskar Skog Mar 06 '17 at 16:16

0 Answers0