简体   繁体   中英

merging contents from two files in one file using shell script

File A :

1
3
5
7

File B:

2
4
6
8

Is is possible to use File A and File B as input in a shell script and get an output which is File C whose contents are as follows:

1
2
3
4
5
6
7
8  

Use paste to interleave the lines in the exact order they're found:

paste -d '\n' filea fileb

Or use sort to combine and sort the files:

sort filea fileb

Simply:

sort -n FileA FileB > FileC

Gives:

1
2
3
4
5
6
7
8
$ cat > filea
1
3
5
7
$ cat > fileb
2
4
6
8 
$ sort -m filea fileb
1
2
3
4
5
6
7
8
$ 

just to make it clear... press ctrl D at the end of each list of numbers for setting up filea and fileb. Thanks Kevin

Since you said you wanted a shell solution,

#!/bin/bash

if [ $# -ne 2 ] ; then
   echo 'usage: interleave filea fileb >out' >&2
   exit 1
fi

exec 3<"$1"
exec 4<"$2"

read -u 3 line_a
ok_a=$?

read -u 4 line_b
ok_b=$?

while [ $ok_a -eq 0 -a $ok_b -eq 0 ] ; do
   echo "$line_a"
   echo "$line_b"

   read -u 3 line_a
   ok_a=$?

   read -u 4 line_b
   ok_b=$?
done

if [ $ok_a -ne 0 -o $ok_b -ne 0 ] ; then
   echo 'Error: Inputs differ in length' >&2
   exit 1
fi

如果您想在第一个文件的末尾附加第二个文件的内容。

cat file1.txt file2.txt > file3.txt 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM