sed edit file in place

前端 未结 13 2066
忘掉有多难
忘掉有多难 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 05:48

    If you are replacing the same amount of characters and after carefully reading “In-place” editing of files...

    You can also use the redirection operator <> to open the file to read and write:

    sed 's/foo/bar/g' file 1<> file
    

    See it live:

    $ cat file
    hello
    i am here                           # see "here"
    $ sed 's/here/away/' file 1<> file  # Run the `sed` command
    $ cat file
    hello
    i am away                           # this line is changed now
    

    From Bash Reference Manual → 3.6.10 Opening File Descriptors for Reading and Writing:

    The redirection operator

    [n]<>word
    

    causes the file whose name is the expansion of word to be opened for both reading and writing on file descriptor n, or on file descriptor 0 if n is not specified. If the file does not exist, it is created.

提交回复
热议问题