≡ Menu

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 
# 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" 
{ 3 comments… add one }
  • Pravin March 5, 2014, 5:07 pm

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

    • nixcraft March 12, 2014, 9:13 am

      Thanks for the heads up!

  • hunterm October 23, 2010, 2:38 am

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

Security: Are you a robot or human?

Leave a Comment