当值包含空格时,如何从bash脚本中打印CSV值

时间:2014-07-16 09:34:23

标签: bash shell csv awk eval

我有以下 CSV 文件(我有linux red-hat 6.2版本)

# 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

以下bash脚本应该读取CSV文件并打印文件PATH FILE1,FILE2,FILE3

备注 - 我仅设置参数 CSV_LINE = 2 (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

所以,如果我运行bash脚本(当我设置 CSV = SIMPLE_FILES.CSV 时),请获取以下内容

 /read_path_from_csv.bash


 /etc/hosts
 /etc/info.txt
 /var/log.txt

直到现在还好,

但如果我运行bash脚本(当我设置 CSV = COMPLEX_FILES.CSV 时),请获取follwoiojng

  ./read_path_from_csv.bash: line 20: ip.txt: command not found

我的结论 - 似乎PATH中的空格导致了这个错误

请建议如何更新我的代码,以便打印 COMPLEX_FILES.CSV 中定义的PATH,

如何在PATH之前添加一个,在PATH之后添加一个

示例应该获取:

/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

1 个答案:

答案 0 :(得分:2)

是的,它是导致此问题的PATH中的空格,您可以添加引号以避免它。

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)

<强>解释

如果您在bash中运行eval 'FILE1=/path/file name',则会出错:

-bash: name: command not found

您可以引用/path/file name部分以避免此错误:

> eval 'FILE1="/path/file name"'
> echo $FILE1
/path/file name