Home » Linux » Appending the contents of a file at the beginning of another file in UNIX [closed]

Appending the contents of a file at the beginning of another file in UNIX [closed]

Posted by: admin January 30, 2018 Leave a comment

Questions:

I know that

cat file1 >> file2 

would append the contents of file1 at the end of file2. On the other hand, how can I append the contents of file1 at the beginning of file 2, and not at its end?

Actually, i have a single master file M, and several other files in a directory D. I want to append the contents of file M at the beginning of all the files in the directory D.

Answers:

For each file you could do:

cat MASTER file >> file.tmp

And then move file.tmp over file.

Questions:
Answers:

Just do:

cat file1 file2 > tmp && mv tmp file2

Questions:
Answers:

You will have to use a temporary file and rename it after merge.

Example:

echo -e "a\nb\nc" > LETTERS
echo -e "1\n2\n3" > NUMBERS 
cat NUMBERS LETTERS > TMP
mv TMP LETTERS
cat LETTERS

Your command might look something like:

for file in $( find -name "*.java" ); do cat PREPEND ${file} > ${file}.tmp; mv ${file}.tmp ${file}; done