In this article we will see how to read a delimited files in shell script. We will use input fileF_Input_File.txt for demonstration purpose.
Input File: F_Input_File.txt
1001|A1|HR|5000|Y
1002|A2|FIN|6000|Y
1003|A3|HR|6000|Y
1004|A4|HR|7000|Y
We can read a file using loop (while, for), here we are reading data from F_Input_File.txt.
V_Line holds the complete record and by using cut we are fetching all the fields.
while read V_Line
do
V_Id=`echo ${V_Line} | cut -d"|" -f1`
V_Name=`echo ${V_Line} | cut -d"|" -f2`
V_Dept=`echo ${V_Line} | cut -d"|" -f3`
V_Sal=`echo ${V_Line} | cut -d"|" -f4`
V_Actv_Ind=`echo ${V_Line} | cut -d"|" -f5`
echo "Employee Id is.........:" ${V_Id}
echo "Employee Name is.......:" ${V_Name}
echo "Employee Department is.:" ${V_Dept}
echo "Employee Salary is.....:" ${V_Sal}
echo "Employee Status is.....:" ${V_Actv_Ind}
done < F_Input_File.txt
Output:
Employee Id is.........: 1001
Employee Name is.......: A1
Employee Department is.: HR
Employee Salary is.....: 5000
Employee Status is.....: Y
Employee Id is.........: 1002
Employee Name is.......: A2
Employee Department is.: FIN
Employee Salary is.....: 6000
Employee Status is.....: Y
Employee Id is.........: 1003
Employee Name is.......: A3
Employee Department is.: HR
Employee Salary is.....: 6000
Employee Status is.....: Y
Employee Id is.........: 1004
Employee Name is.......: A4
Employee Department is.: HR
Employee Salary is.....: 7000
Employee Status is.....: Y
We can get the same output by using IFS keyword (Internal Field Separator), here data is stored in associated variables separated by pipe(|). By using IFS, we can reduce the code and implement the same with the ease.
IFS="|"
while read V_Id V_Name V_Dept V_Sal V_Actv_Ind
do
echo "Employee Id is.........:" ${V_Id}
echo "Employee Name is.......:" ${V_Name}
echo "Employee Department is.:" ${V_Dept}
echo "Employee Salary is.....:" ${V_Sal}
echo "Employee Status is.....:" ${V_Actv_Ind}
done < F_Input_File.txt
Output:
$ sh a.sh
Employee Id is.........: 1001
Employee Name is.......: A1
Employee Department is.: HR
Employee Salary is.....: 5000
Employee Status is.....: Y
Employee Id is.........: 1002
Employee Name is.......: A2
Employee Department is.: FIN
Employee Salary is.....: 6000
Employee Status is.....: Y
Employee Id is.........: 1003
Employee Name is.......: A3
Employee Department is.: HR
Employee Salary is.....: 6000
Employee Status is.....: Y
Employee Id is.........: 1004
Employee Name is.......: A4
Employee Department is.: HR
Employee Salary is.....: 7000
Employee Status is.....: Y
Conclusion: By using similar method we can read any kind of delimited file like CSV file (comma delimited)
Keep Reading, Keep Learning, Keep Sharing...!!!