tags:

views:

167

answers:

4

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.txt": 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?

+3  A: 

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.)

Beta
+2  A: 

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
lhf
+1  A: 
awk '/STUFFGOESHERE/{while((getline line<"file1")>0){ print line};next}1' file2
ghostdog74
+1  A: 

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
reinierpost
For some reason which I can't see why the text file is either put in after the other file, and not after STUFFGOESHERE
S1syphus
Your sentence is malformed, but I'll guess what you mean. The main reason is that I write all of my scripts to take their input either from standard input or from files named as arguments. I never hardcode them into the script. This is a matter of fundamental scripting hygiene. Another reason is that Perl doesn't have a function that takes a filename and returns the file's contents, like PHP does.
reinierpost