解析CSV在bash和分配变量 [英] Parse CSV in bash and assign variables

查看:145
本文介绍了解析CSV在bash和分配变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的格式(在Linux上的Bash工作)

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

DN , MAC , Partition ,  

123 , abc , xyz  
321 , asd , asd 

我能够用awk它通过使用解析

I am able to parse it using awk by using

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

这是在CSV每一列完成,因此我可以叫 DN [2] MAC [2] 等分别是手动和单独解析他们。

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 123 ,相应的 MAC 分区也应退还。

But how can I parse the csv by row? For example : If I call for DN is 123, the corresponding MAC and Partition should also be returned.

推荐答案

尝试一个循环:

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


要选择一个记录,你可以使用一个case语句:


To select a record you could use a case statement:

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

这篇关于解析CSV在bash和分配变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆