sed edit file in place

前端 未结 13 1658
忘掉有多难
忘掉有多难 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:57

    Like Moneypenny said in Skyfall: "Sometimes the old ways are best." Kincade said something similar later on.

    $ printf ',s/false/true/g\nw\n' | ed {YourFileHere}
    

    Happy editing in place. Added '\nw\n' to write the file. Apologies for delay answering request.

    0 讨论(0)
  • 2020-11-22 05:59

    Versions of sed that support the -i option for editing a file in place write to a temporary file and then rename the file.

    Alternatively, you can just use ed. For example, to change all occurrences of foo to bar in the file file.txt, you can do:

    echo ',s/foo/bar/g; w' | tr \; '\012' | ed -s file.txt
    

    Syntax is similar to sed, but certainly not exactly the same.

    Even if you don't have a -i supporting sed, you can easily write a script to do the work for you. Instead of sed -i 's/foo/bar/g' file, you could do inline file sed 's/foo/bar/g'. Such a script is trivial to write. For example:

    #!/bin/sh -e
    IN=$1
    shift
    trap 'rm -f $tmp' 0
    tmp=$( mktemp )
    <$IN "$@" >$tmp && cat $tmp > $IN  # preserve hard links
    

    should be adequate for most uses.

    0 讨论(0)
  • 2020-11-22 06:00

    The -i option streams the edited content into a new file and then renames it behind the scenes, anyway.

    Example:

    sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename
    

    and

    sed -i '' 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename
    

    on macOS.

    0 讨论(0)
  • 2020-11-22 06:03

    The following works fine on my mac

    sed -i.bak 's/foo/bar/g' sample
    

    We are replacing foo with bar in sample file. Backup of original file will be saved in sample.bak

    For editing inline without backup, use the following command

    sed -i'' 's/foo/bar/g' sample
    
    0 讨论(0)
  • 2020-11-22 06:05

    On a system where sed does not have the ability to edit files in place, I think the better solution would be to use perl:

    perl -pi -e 's/foo/bar/g' file.txt
    

    Although this does create a temporary file, it replaces the original because an empty in place suffix/extension has been supplied.

    0 讨论(0)
  • 2020-11-22 06:05

    Very good examples. I had the challenge to edit in place many files and the -i option seems to be the only reasonable solution using it within the find command. Here the script to add "version:" in front of the first line of each file:

    find . -name pkg.json -print -exec sed -i '.bak' '1 s/^/version /' {} \;
    
    0 讨论(0)
提交回复
热议问题