Using sed replace line in file with another file

后端 未结 4 1571
我寻月下人不归
我寻月下人不归 2021-01-21 08:04

I have a very large tab delimited file, I would like to replace a single line in this file with another. As the line has >100 columns, a simple sed \'s/find/replace/\' is not de

4条回答
  •  清酒与你
    2021-01-21 08:59

    Based on GNU sed 4.2.2, also includes answers from Cyrus and Aaron

    $ cat foo.txt 
    1 abc
    2 ijk!
    3 pqr
    4 xyz
    
    $ cat f1.txt 
    a/b/c
    
    $ cat f2.txt 
    line
    
    $ cat f3.txt 
    line a
    line b
    


    1) Pattern and replacement not containing characters that'll affect sed command or act weirdly due to bash substitution inside double quotes

    $ sed "/3/c $(< f2.txt)" foo.txt 
    1 abc
    2 ijk!
    line
    4 xyz
    
    $ sed "s/.*3.*/$(< f2.txt)/" foo.txt 
    1 abc
    2 ijk!
    line
    4 xyz
    
    $ sed -e '/3/{r f2.txt' -e 'd}' foo.txt 
    1 abc
    2 ijk!
    line
    4 xyz
    


    2) Pattern getting affected due to bash substitution

    $ sed "/!/c $(< f2.txt)" foo.txt 
    bash: !/c: event not found
    
    $ sed '/!/c '"$(< f2.txt)" foo.txt
    1 abc
    line
    3 pqr
    4 xyz
    
    $ sed "s/.*!.*/$(< f2.txt)/" foo.txt 
    bash: !.*/$: event not found
    
    $ sed 's/.*!.*/'"$(< f2.txt)/" foo.txt
    1 abc
    line
    3 pqr
    4 xyz
    
    $ sed -e '/!/{r f2.txt' -e 'd}' foo.txt 
    1 abc
    line
    3 pqr
    4 xyz
    


    3) Replacement line (single line only) containing characters affecting sed

    $ sed "/3/c $(< f1.txt)" foo.txt 
    1 abc
    2 ijk!
    a/b/c
    4 xyz
    
    $ sed "s/.*3.*/$(< f1.txt)/" foo.txt
    sed: -e expression #1, char 11: unknown option to `s'
    
    $ sed "s|.*3.*|$(< f1.txt)|" foo.txt
    1 abc
    2 ijk!
    a/b/c
    4 xyz
    
    $ sed -e '/3/{r f1.txt' -e 'd}' foo.txt
    1 abc
    2 ijk!
    a/b/c
    4 xyz
    


    4) Replacement with multiple lines

    $ sed "/3/c $(< f3.txt)" foo.txt 
    sed: -e expression #1, char 14: extra characters after command
    
    $ sed "s/.*3.*/$(< f3.txt)/" foo.txt
    sed: -e expression #1, char 14: unterminated `s' command
    
    $ sed -e '/3/{r f3.txt' -e 'd}' foo.txt
    1 abc
    2 ijk!
    line a
    line b
    4 xyz
    

提交回复
热议问题