sed edit file in place

前端 未结 13 1699
忘掉有多难
忘掉有多难 2020-11-22 05:20

I am trying to find out if it is possible to edit a file in a single sed command without manually streaming the edited content into a new file and

相关标签:
13条回答
  • 2020-11-22 06:14

    One thing to note, sed cannot write files on its own as the sole purpose of sed is to act as an editor on the "stream" (ie pipelines of stdin, stdout, stderr, and other >&n buffers, sockets and the like). With this in mind you can use another command tee to write the output back to the file. Another option is to create a patch from piping the content into diff.

    Tee method

    sed '/regex/' <file> | tee <file>
    

    Patch method

    sed '/regex/' <file> | diff -p <file> /dev/stdin | patch
    

    UPDATE:

    Also, note that patch will get the file to change from line 1 of the diff output:

    Patch does not need to know which file to access as this is found in the first line of the output from diff:

    $ echo foobar | tee fubar
    
    $ sed 's/oo/u/' fubar | diff -p fubar /dev/stdin
    *** fubar   2014-03-15 18:06:09.000000000 -0500
    --- /dev/stdin  2014-03-15 18:06:41.000000000 -0500
    ***************
    *** 1 ****
    ! foobar
    --- 1 ----
    ! fubar
    
    $ sed 's/oo/u/' fubar | diff -p fubar /dev/stdin | patch
    patching file fubar
    
    0 讨论(0)
提交回复
热议问题