The CSV file, or list of comma-separated values, will come from the file named tools that we have in a current directory. This is a catalog of products that we sell. The file content is shown in the following output:
drill,99,5 hammer,10,50 brush,5,100 lamp,25,30 screwdriver,5,23 table-saw,1099,3
This is just a simple demonstration, so we don't expect too much data, but each item in the catalog consists of the following:
- Name
- Price
- Units in stock
We can see that we have a drill that costs $99 and we have five units in stock. If we list the file with cat, it is not very friendly; however, we can write a script to display the data in a more appealing way. We can create a new script called $HOME/bin/parsecsv.sh:
#!/bin/bash OLDIFS="$IFS" IFS="," while read product price quantity do echo -e "33[1;33m$product ======================== 33[0m Price : $price Quantity : $quantity " done <"$1" IFS=$OLDIFS
Let's work through this file and look at the pertinent elements:
Element |
Meaning |
OLDIFS="$IFS" |
The IFS variable stores the file separator and this is normally a white space character. We can store the old IFS so that we can restore it later at the end of the script, ensuring that we return the same environment once the script is complete, no matter how the script is run. |
IFS="," |
We set the separator to a comma to match what we need with a CSV file. |
while read product price quantity |
We enter a while loop to populate three variables that we need: product, price, and quantity. The while loop will read the input file, line by line, and populate each of the variables. |
echo ... |
The echo command displays the product name in blue with double underscores underneath. The other variables are printed on new lines and tabbed in. |
done <"$1" |
This is where we read the input file, which we pass as an argument to the script. |
The script is shown in the following screenshot:
We can execute the script with the tools catalog file located in the current directory using the following command:
$ parsecsv.sh tools
To look at how this will display, we can view the partial output in the following screenshot:
We are now starting to get the idea that we have a lot of power at the command line to format files in a more readable way and a plain text file does not need to be plain.