0

I have a CSV file which contains the field names and values. The field names have given with a '#' Eg.

test.csv

#field_1,field_2,field_3
1,axt,3
2,bss,3

I need to display the output like this:

heading_1=field_1
heading_2=field_2
heading_3=field_3

The script I have written so far:

headings=$(grep '^#' $arg_file)
echo "Fields name= $headings"

###### put a for loop to take in all headings as separate variables
for ((i=1; i<=$(echo "$headings"|tr ',' ' '|wc -w); i++))
do
    echo "Trial $i field"
    heading_$i=$(echo "$headings"|cut -d "," -f $i)
    var="$(heading_$i)"
    echo ${!var}
done

But this is giving me an error:

./script.sh: line 28: heading_1=#field_1: command not found
./script.sh: line 29: heading_1: command not found

What should I do to get the output the way I want? I am new to shell script and I am not really sure if that is even possible.

user3140427
  • 19
  • 1
  • 3
  • This is [BashFAQ #6](http://mywiki.wooledge.org/BashFAQ/006). – Charles Duffy Jul 18 '17 at 16:56
  • btw, the `sh` tag is for POSIX-compliant shell scripts. Your existing code already has a bunch of requirements for bash and isn't expected to work with POSIX sh. – Charles Duffy Jul 18 '17 at 16:57
  • in `var="$(heading_$i)"`, btw, that's a *command substitution*, calling a string that starts with `heading_` as an executable. It's surely not what you want. `var=heading_$i; echo "${!var}"` is closer to being the Right Thing. – Charles Duffy Jul 18 '17 at 16:58
  • "${!var}" was still showing errors. I made it an array and it turned out okay. – user3140427 Jul 21 '17 at 21:19
  • Huh. It's a perfectly fine approach -- you can copy-and-paste the following to see it work: `heading_1="First"; num=1; var="heading_$num"; echo "${!var}"` – Charles Duffy Jul 21 '17 at 21:23

0 Answers0