简体   繁体   中英

Using sed replace line in file with another file

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 desirable. My newline is stored in file newline.txt

How do I achieve:

sed 's/find/newline.txt/' infile

With GNU sed:

Find line in file file.csv which contains find , append content ( r ) of file newline.txt and delete ( d ) line which contains find :

sed -e '/find/{r newline.txt' -e 'd}' file.csv

From @Aaron

sed "s/^.*find.*$/$(cat newline.txt)/" infile.txt

Where find is a unique string in infile.txt that returns a single line, the line is then replaced by newline.txt

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

尝试这个

sed s/find/$(< newline.txt)/ infile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM