Using sed to insert text file at first line

sed '1r file.txt' <source.txt >desti.txt

This example will insert 'file.txt' between line 1 and 2 of source.txt.

sed '0r file.txt' <source.txt >desti.txt

gives an error message.

Does anyone know how 'sed' can insert 'file.txt' before the first line of source.txt?

Does it have to be sed?

awk 'NR==1{system("cat file.txt")}1' source.txt >desti.txt
cat file.txt source.txt >desti.txt

:smiley:

Bah, I feel silly now... :wink:

@Bartus

LOL , you geek :wink:

Why sed and not cat?

I suppose you could do something like sed : file1 file2

sed '1s/^/New first line\^J/' inp_file

Where ^J is entered as two different key strokes:
<ctl-v> and <enter>

 perl -e 'local $/;open A,"file.txt";open B,"source.txt";open C,">desti.txt";print C <A> . <B>'

:smiley:

Actually, I wanted to find a batch script that applies this insert 'file.txt' to all .c files in the current directory. So, in that case awk might be the best solution I guess:

find . -name "*.c" - exec awk 'NR==1{system("cat file.txt")}1' {} >{} \;

however, this command will wipe out all the contents in all .c files.
How do I further improve this script?

Thx.

Try:

for file in *.c
do
  cat file.txt "$file" > tempfile && mv tempfile "$file"
done

Yes but (just in case) if you care about keeping inodes of the $file you should

cat tempfile >"$file" ; rm tempfile instead of the mv

In that case you can remove the tempfile after the loop instead of in the loop:

for file in *.c
do
  cat file.txt "$file" > tempfile
  cat tempfile > "$file"
done
rm tempfile

Obviously :smiley:

Thanks guys. One more difficulty. I run the following script from cygwin:

#!/bin/bash
for file in *.c
do
cat Head.c "$file" > tempfile && mv tempfile "$file"
done

...and get the following error:

./insert.sh: line 3: syntax error near unexpected token `$'do\r''
'/insert.sh: line 3: `do

..hmmm...what did I wrong?

Cygwin allows you to use either CR/LF or LF line endings - it's a registry key setting, IIRC.

Try running dos2unix on your shell script to change CR/LF to LF.

Excellent! Thanks guys. I appreciate all your help.

I completely missed page 2 of this thread when I wrote the following :o

I like ctsgnb's cat suggestion. However, if your life depends on using sed, you could swap the order of files:

sed '$r source.txt' < file.txt > desti.txt

If this is part of a larger sed task and swapping the order is not palatable, and if you are certain that there's more than one line in source.txt, you could use the following in a sed script:

1 {
    r file.txt
    h
    d
}

2 {
    H
    g
}

Regards,
Alister

What is the 'H' command doing? Why is it required?

H appen newline + patternspace into the hold space
h would replace instead of appen