Prepend data from one file to another

雨燕双飞 提交于 2019-11-30 13:47:30

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

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

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

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.

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.

This script uses 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 will 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]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!