Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend data from one file to another

How do I prepend the data from file1.txt to file2.txt?

like image 330
Sukesh Avatar asked Jun 28 '12 17:06

Sukesh


People also ask

How do you prepend text in Linux?

1s;^;to be prepended; substitutes the beginning of the first line by the given replacement string, using ; as a command delimiter.

How do you add append a file file1 to file2?

This can be done quite simply in bash and other shells by using '>>' to append the contents with the 'cat' command, as shown below. First we'll create our example files. Now we will concatenate these files together, by adding file2 to the bottom of file1.


2 Answers

The following command will take the two files and merge them into one

cat file1.txt file2.txt > file3.txt; mv file3.txt file2.txt
like image 115
Justin.Wood Avatar answered Sep 29 '22 08:09

Justin.Wood


If it's available on your system, then sponge from moreutils is designed for this. Here is an example:

cat file1.txt file2.txt | sponge file2.txt

If you don't have sponge, then the following script does the same job using a temporary file. It makes sure that the temporary file is not accessible by other users, and cleans it up at the end.

If your system, or the script crashes, you may need to clean up the temporary file manually. Tested on Bash 4.4.23, and Debian 10 (Buster) Gnu/Linux.

#!/bin/bash
#
# ---------------------------------------------------------------------------------------------------------------------- 
# usage [ from, to ]
#       [ from, to ]
# ---------------------------------------------------------------------------------------------------------------------- 
# Purpose:
# Prepend the contents of file [from], to file [to], leaving the result in file [to].
# ---------------------------------------------------------------------------------------------------------------------- 

# check 
[[ $# -ne 2 ]] && echo "[exit]: two filenames are required" >&2 && exit 1

# init
from="$1"
to="$2"
tmp_fn=$( mktemp -t TEMP_FILE_prepend.XXXXXXXX )
chmod 600 "$tmp_fn"

# prepend
cat "$from" "$to" > "$tmp_fn"
mv "$tmp_fn" "$to"

# cleanup
rm -f "$tmp_fn"

# [End]
like image 41
freeB Avatar answered Sep 29 '22 09:09

freeB