Appending files in Unix

Two or more files can be appended in Linux using 'cat' command.

cat fileName1,fileName2 > fileName3

The above command will append the contents of fileName2 in fileName1 and the resulting data will be available in fileName3.

Consider there are two files emp.txt(contains empId:empName) and designation.txt(contains empId:designation).

emp.txt

100:CHRIS
101:MARTIN

designation.txt

100:HR
101:SYSTEM_ANALYST

Suppose if there is a requirement to create a new file empDetails.txt (containing empId:empName:designation) by combining data from above two files

We can do so by using the following shell script.

empData.sh

#!/usr/bin
cat $1 | awk -F: '{print $1}' > empId.txt
for empName in `cat empId.txt`
do
      designation=`cat $2  | sed  -n "s/${empName}\:\(.*\)/\1/p"`
      data=`cat $1 | sed  -n "s/\(${empName}\)\:\(.*\)/\1:\2:${designation}/p"`
      echo $data >> empDetails.txt
done

Note that we use 'echo' command with '>>' operator to append data in to 'empDetails.txt' file in the above shell script.

Execute the above script by passing the above two files as parameters as follows

sh empData.sh emp.txt designation.txt

The output of the resulting file is as follows
empDetails.txt

100:CHRIS:HR
101:MARTIN:SYSTEM_ANALYST
Technology: 

Search