Karthik Karthik - 1 year ago 42
Bash Question

shell parse csv file, assign fields to variable and print it in multiple columns

Im trying to curl a csv file and parse it based on their property and print it back by using variable names.

File 1:,gateway,name_of_device,server,name_of_device,PC,name_of_device

My script below,


input=$(curl http://example.com/1.txt)

ip=$(echo "$input" | awk -F ',' '{print $1}')
type=$(echo "$input" | awk -F ',' '{print $2}')
name=$(echo "$input" | awk -F ',' '{print $3}')

echo "$ip $type $name"

This prints,

but the expected output should be like, gateway name_of_device server name_of_device PC name_of_device

Tried different options like,

assigning output to another variable and echo'ing it,

# output="$source_ip $tag_text"
# echo -e $output

printf statements:

# printf "%-20s | %-20s" "$source_ip" "$tag_text"

# printf "$source_ip" "$tag_text"

Answer Source

awk is certainly the correct tool to use for this, but you can also do:

curl http://example.com/1.txt |
while IFS=, read ip type name rest; do
  echo $ip $type $name

The variables will lose their value after the while loop finishes, since it is in a sub-shell.