Use the contents of a file to replace a string using SED

后端 未结 2 1600
小鲜肉
小鲜肉 2021-01-01 10:22

What would be the sed command for mac shell scripting that would replace all iterations of string \"fox\" with the entire string content of myFile.txt.

myFile.txt wo

2条回答
  •  难免孤独
    2021-01-01 10:28

    You can use the r command. When you find a 'fox' in the input...

    /fox/{
    

    ...replace it for nothing...

        s/fox//g
    

    ...and read the input file:

        r f.html
    }
    

    If you have a file such as:

    $ cat file.txt
    the
    quick
    brown
    fox
    jumps
    over
    the lazy dog
    fox dog
    

    the result is:

    $ sed '/fox/{
        s/fox//g
        r f.html
    }' file.txt
    the
    quick
    brown
    
        

jumps over the lazy dog dog

EDIT: to alter the file being processed, just pass the -i flag to sed:

sed -i '/fox/{
    s/fox//g
    r f.html
}' file.txt

Some sed versions (such as my own one) require you to pass an extension to the -i flag, which will be the extension of a backup file with the old content of the file:

sed -i.bkp '/fox/{
    s/fox//g
    r f.html
}' file.txt

And here is the same thing as a one liner, which is also compatible with Makefile

sed -i -e '/fox/{r f.html' -e 'd}'

提交回复
热议问题