Sukesh
Sukesh

Reputation: 323

Prepend data from one file to another

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

Upvotes: 14

Views: 10074

Answers (5)

freeB
freeB

Reputation: 101

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]

Upvotes: 2

janos
janos

Reputation: 124646

Another way using GNU sed:

sed -i -e '1rfile1.txt' -e '1{h;d}' -e '2{x;G}' file2.txt

That is:

  • On line 1, append the content of the file file1.txt
  • On line 1, copy pattern space to hold space, and delete pattern space
  • On line 2, exchange the content of the hold and pattern spaces, and append the hold space to pattern space

The reason it's a bit tricky is that the r command appends content, and line 0 is not addressable, so we have to do it on line 1, moving the content of the original line out of the way and then bringing it back after the content of the file is appended.

Upvotes: 7

janos
janos

Reputation: 124646

You can do this in a pipeline using sponge from moreutils:

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

Upvotes: 7

Justin.Wood
Justin.Wood

Reputation: 715

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

Upvotes: 26

Hao Liu
Hao Liu

Reputation: 122

The way of writing file is like 1). append at the end of the file or 2). rewrite that file.

If you want to put the content in file1.txt ahead of file2.txt, I'm afraid you need to rewrite the combined fine.

Upvotes: -1

Related Questions