Reputation: 7400
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
Upvotes: 3
Views: 19512
Reputation: 47
If you want to append the second file contents at the end of first file.
cat file1.txt file2.txt > file3.txt
Upvotes: 0
Reputation: 385590
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
Upvotes: 1
Reputation: 34307
$ 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
Upvotes: 2
Reputation: 361575
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
Upvotes: 10