Q) How to parse CVS files and print the contents on the terminal using the bash shell script in Unix or Linux system?
It is the most common operation in Unix system to read the data from a delimited file and applying some operations on the data. Here we see how to read the Comma separated value (CSV) file using the while loop in shell script and print these values on the Unix terminal.
> cat os_server.csv
Unix, dedicated server
Linux, virtual server
This file contains two fields. First field is operating system and the second field contains the hosting server type. Let see how to parse this CVS file with simple bash script shown below:
#!/usr/bin/bash
INPUT_FILE='unix_file.csv'
IFS=','
while read OS HS
do
echo "Operating system - $OS"
echo "Hosting server type - $HS"
done < $INPUT_FILE
Here IFS is the input field separator. As the file is comma delimited, the IFS variable is set with comma. The output of the above script is
Operating system - Unix
Hosting server type - dedicated server
Operating system - Linux
Hosting server type - virtual server
Here in the code, the fourth line (IFS=',') and sixth line (while) can be merged into a single statement as shown below:
while IFS=',' read OS HS
0 comments:
Post a Comment