

For example, with the program (called script.sh) #!/bin/bash

Let’s check the script output: array of SNos : 1 2Īrray of Value : 40 50 5.One alternative way to do this would be to just redirect standard input to your file, where you have all the user input in the order it's expected by the program. Notably, the first set of parentheses is required to hold the output of the command substitution in variable arr_record1 as an array. Now we’ll check methods to parse entire columns of CSV into Bash arrays: #! /bin/bashĪrr_record1=( $(tail -n +2 input.csv | cut -d ',' -f1) )Īrr_record2=( $(tail -n +2 input.csv | cut -d ',' -f2) )Īrr_record3=( $(tail -n +2 input.csv | cut -d ',' -f3) )Īrr_record4=( $(tail -n +2 input.csv | cut -d ',' -f4) )Įcho "array of SNos : "array of Qty : "array of Price : "array of Value : using command substitution to exclude the header line using the tail command, and then using the cut command to filter the respective columns. In the previous section, we parsed the field values into Bash variables for each record. We’ll save the above script as parse_csv.sh for execution: Next, we searched the column name in the output using the grep command, and truncated the preceding spaces using the tr command.įinally, we used the awk command to get the first field, which corresponds to the column number. Then we appended the line number at the beginning of each line using the nl command. We calculated the location of a column using a combination of the tr, awk, grep, and nlcommands.įirst, we converted the commas in the header line into line-breaks using the tr command. This script takes col_b as input from the user, and prints the corresponding column value for every record in the file. Read -p "Enter the column name to be printed for each record: " col_b

We’ll illustrate this with a simple user-input-driven script: #! /bin/bash There can be situations where we might need to parse the values from CSV based on column names in the header line.
