Shell Script To Combine Any Three Text Files Into a Single File

#!/bin/bash
# Write a shell script to combine any three text files into a single file
# (append them in the order as then appear in the arguments) and display 
# the word count.
# -------------------------------------------------------------------------
# Copyright (c) 2001 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
file1=$1
file2=$2
file3=$3
out="output.$$"
count=0
 
if [ $# -ne 3 ]
then
	echo "$(basename $0) file1 file2 file3"
	exit 1
fi
 
if [ ! -f $file1 ] 
then
	echo "$file1 not a file!"
	exit 2
fi
 
if [ ! -f $file2 ] 
then
	echo "$file2 not a file!"
	exit 3
fi
 
if [ ! -f $file3 ] 
then
	echo "$file3 not a file!"
	exit 4 
fi
 
cat $file1 $file2 $file3 >> $out
count=$(cat $out | wc -w)
echo "$count words written to $out"
Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
CategoryList of Unix and Linux commands
File Management cat
Firewall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN CentOS 8 Debian 10 Firewall Ubuntu 20.04
3 comments… add one
  • Pravin Mar 5, 2014 @ 17:07

    There is a typo error on line 36:
    if [ ! -f $file ]
    should be
    if [ ! -f $file3 ]

    • nixcraft Mar 12, 2014 @ 9:13

      Thanks for the heads up!

  • hunterm Oct 23, 2010 @ 2:38

    There’s also this really nice command called:
    $ cat file1 file2 file3 >combine

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.