Reputation: 1702
I have the following CSV files ( I have linux red-hat 6.2 version )
# more SIMPLE_FILES.CSV
FILE1,FILE2,FILE3
/etc/hosts,/etc/info.txt,/var/log.txt
/etc/some_file,/var/collect.txt,/etc/INFO.txt
/sbin/ls,/sbin/awk,/sbin/sed
# more COMPLEX_FILES.CSV
FILE1,FILE2,FILE3
/etc/config/net ip.txt,/var/log/summary snap/LOG OF global/info.txt
/etc/hosts files hosts.info/etc/hosts,var/log/messages,/sbin/collect file/all.info
/etc/old/TEXT INFO/info.txt/etc/OLD FILES/info.txt,/root/customor select/info.txt
the following bash script should read the CSV file and print the files PATH for FILE1,FILE2,FILE3
remark - I set the param CSV_LINE=2 only for example ( the second values in CSV )
#!/bin/bash
CSV=SIMPLE_FILES.CSV
CSV_LINE=2
eval $(awk -v A=$CSV_LINE -F, 'NR==1 { for (i=1; i<=NF; i++) sn[i]=$i }
NR==A { for (i=1; i<=NF; i++) print sn[i] "=" $i; exit }' $CSV )
echo $FILE1
echo $FILE2
echo $FILE3
so if I run the bash script ( when I set CSV=SIMPLE_FILES.CSV ) get the following
/read_path_from_csv.bash
/etc/hosts
/etc/info.txt
/var/log.txt
until now its fine,
but if I run the bash script ( when I set CSV=COMPLEX_FILES.CSV ) get the follwoiojng
./read_path_from_csv.bash: line 20: ip.txt: command not found
My conclusion - its seems that the spaces in the PATH cause for this error
please advice how to update my code in order to print the PATH as defined in the COMPLEX_FILES.CSV ,
How to add one " before PATH and one " after the PATH ?
Example what I should to get:
/read_path_from_csv.bash
/etc/config/net ip.txt,/var/log/summary snap/LOG OF global/info.txt
/etc/hosts files hosts.info/etc/hosts,var/log/messages,/sbin/collect file/all.info
/etc/old/TEXT INFO/info.txt/etc/OLD FILES/info.txt,/root/customor select/info.txt
Upvotes: 1
Views: 860
Reputation: 7255
Yes, it the spaces in the PATH that causing this problem, and you can add quotes to avoid it.
eval $(awk -v A=$CSV_LINE -v q='"' -F, 'NR==1 { for (i=1; i<=NF; i++) sn[i]=$i }
NR==A { for (i=1; i<=NF; i++) print sn[i] "=" q $i q; exit }' $CSV)
Explanation:
If you run eval 'FILE1=/path/file name'
in bash, it will give an error:
-bash: name: command not found
And you can quotes the /path/file name
part to avoid this error:
> eval 'FILE1="/path/file name"'
> echo $FILE1
/path/file name
Upvotes: 2