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

I have two text files, I want to put text in the middle of another, I did some research and found information on adding individual lines:

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

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

sed: 1: "/ ^ STUFFGOESHERE / a long.txt": a command expects \ followed by text

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

Any ideas?

+3
source share
4 answers

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 change file2 in place:

sed -i -e...

(, , sed -i '' -e..., GNU sed 4.1.5.)

+5

ex ed,

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

script ed:

cat <<EOF | ed file2.txt
/^STUFFGOESHERE/
.r file1.txt
w
q
EOF
+2
awk '/STUFFGOESHERE/{while((getline line<"file1")>0){ print line};next}1' file2
+1
source

From the 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
+1
source

Source: https://habr.com/ru/post/1741776/


All Articles