开发者

Merge two text files at a specific location, sed or awk

I have two text files, I want to place a text in the middle of another, I did some research and found information about adding single strings:

I have a comment in the second text file called STUFFGOESHERE, so I tried:

sed '/^STUFFGOESHERE/a file1.txt' file2.txt 

sed: 1: "/^STUFFGOESHERE/a long.开发者_StackOverflowtxt": command a expects \ followed by text

So I tried something different, trying to place the contents of the text based on a given line, but no luck.

Any ideas?


This should do it:

sed '/STUFFGOESHERE/ r file1.txt' file2.txt

If you want to remove the STUFFGOESHERE line:

sed -e '/STUFFGOESHERE/ r file1.txt' -e '/STUFFGOESHERE/d' file2.txt

If you want to modify file2 in place:

sed -i -e...

(or maybe sed -i '' -e..., I'm using GNU sed 4.1.5.)


If you can use ex or ed, try

cat <<EOF | ex -e - file2.txt
/^STUFFGOESHERE/
.r file1.txt
w
q
EOF

The same script works for ed:

cat <<EOF | ed file2.txt
/^STUFFGOESHERE/
.r file1.txt
w
q
EOF


awk '/STUFFGOESHERE/{while((getline line<"file1")>0){ print line};next}1' file2


From a Unix shell (bash, csh, zsh, whatever):

: | perl -e '@c = join("", map {<>} 0..eof); print $c[0] =~ /STUFFGOESHERE/ ? $` . $c[1] . $'"'"' : $c[0]' file2.txt file1.txt > newfile2.txt
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜