bash 在bash中解析CSV并分配变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15350208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:49:13  来源:igfitidea点击:

Parse CSV in bash and assign variables

linuxbashparsingcsvawk

提问by Kaptain K

I have a csv of the format (Working on Bash on linux)

我有一个 csv 格式(在 linux 上使用 Bash)

DN , MAC , Partition ,  

123 , abc , xyz  
321 , asd , asd 

I am able to parse it using awk by using

我可以通过使用 awk 来解析它

eval MAC=($(awk -F "," '{print }' random.csv))

This is done for each column in the CSV and therefore I can call DN[2], MAC[2]etc individually which is manual and parses them individually.

这是针对 CSV 中的每一列完成的,因此我可以单独调用DN[2], MAC[2]etc ,这是手动的并单独解析它们。

But how can I parse the csv by row? For example : If I call for DNis 123, the corresponding MACand Partitionshould also be returned.

但是如何逐行解析 csv?例如:如果我调用DNis 123,相应的MACandPartition也应该返回。

回答by Scrutinizer

Try a loop:

尝试循环:

while IFS=, read dn mac partition
do 
  echo "Do something with $dn   $mac and $partition"
done < file


To select a record you could use a case statement:

要选择记录,您可以使用 case 语句:

P2=123
while IFS=, read dn mac partition
do 
  case $dn in
    ($P2) echo echo "Do something with $dn   $mac and $partition" ;;
    (*)   echo "Do nothing" ;;
  esac
done < file

回答by Gilles Quenot

Using awk:

使用awk

read -p "Gimme the DN integer >>> " i
awk -v i=$i -F' , ' '
    NR>1{
        dn[NR]=
        mac[NR]=
        partition[NR]=
    }
    END{
        for (a=2; a<=NR; a++)
            if (i == dn[a])
                print dn[a], mac[a], partition[a]
    }
' file.txt

回答by WYSIWYG

you can also try this

你也可以试试这个

file1 stores all the DN for which you want to retrieve the information

file1 存储您要检索其信息的所有 DN

#parse.awk

BEGIN { FS="," ; OFS= "\t"}

FNR==NR{ a[]; next }

 in a { print ,,}

call awk -f parse.awk file1 csvfile.csv

称呼 awk -f parse.awk file1 csvfile.csv