insert the contents of a file to another (in a specific line of the file that is sent)-BASH/LINUX

I'd probably use sed for this job:

line=3
sed -e "${line}r file2" file1

If you're looking to overwrite file1 and you have GNU sed, add the -i option. Otherwise, write to a temporary file and then copy/move the temporary file over the original, cleaning up as necessary (that's the trap stuff below). Note: copying the temporary over the file preserves links; moving does not (but is swifter, especially if the file is big).

line=3
tmp="./sed.$$"
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15
sed -e "${line}r file2" file1 > $tmp
cp $tmp file1
rm -f $tmp
trap 0

Just for fun, and just because we all love ed, the standard editor, here's an ed version. It's very efficient (ed is a genuine text editor)!

ed -s file2 <<< $'3r file1\nw'

If the line number is stored in the variable line then:

ed -s file2 <<< "${line}r file1"$'\nw'

Just to please Zack, here's one version with less bashism, in case you don't like bash (personally, I don't like pipes and subshells, I prefer herestrings, but hey, as I said, that's only to please Zack):

printf "%s\n" "${line}r file1" w | ed -s file2

or (to please Sorpigal):

printf "%dr %s\nw" "$line" file1 | ed -s file2

As Jonathan Leffler mentions in a comment, and if you intend to use this method in a script, use a heredoc (it's usually the most efficient):

ed -s file2 <<EOF
${line}r file1
w
EOF

Hope this helps!

P.S. Don't hesitate to leave a comment if you feel you need to express yourself about the ways to drive ed, the standard editor.


cat file1 >>file2

will append content of file1 to file2.

cat file1 file2

will concatenate file1 and file2 and send output to terminal.

cat file1 file2 >file3

will create or overwite file3 with concatenation of file1 and file2

cat file1 file2 >>file3

will append concatenation of file1 and file2 to end of file3.

Edit:

For trunking file2 before adding file1:

sed -e '11,$d' -i file2 && cat file1 >>file2

or for making a 500 lines file:

n=$((500-$(wc -l <file1)))
sed -e "1,${n}d" -i file2 && cat file1 >>file2

Tags:

Linux

Shell

Bash