简体   繁体   English

如何读取 CSV 文件并以 arrays Bash 脚本的形式存储?

[英]How to read a CSV File and store it in the form of arrays Bash script?

My CSV file:我的 CSV 文件:

Interface   PHY Protocol    Description
Eth0/0/1    up  up  ***Another-Text-Here***
Eth0/0/2    up  up  ***Some-Text-Here***
Eth0/0/3    up  up  ***Connected-to-Camera***
Eth0/0/4    up  up  ***Some-Services-Ltd***

I want to show in the same format while executing the bash file我想在执行 bash 文件时以相同的格式显示

CSV means comma separated values but there is a possibility that non-comma field separators are used. CSV 表示逗号分隔值,但有可能使用非逗号字段分隔符。 CSV file format is not fully standardised. CSV 文件格式未完全标准化。 So we can give the benefit of doubt to the "Question asker" that the delimiter here in the question is tab or space.因此,我们可以对“问题提问者”提出疑问,即问题中的分隔符是制表符或空格。 You can visit the wiki which also highlights the same thing in its 3rd paragraph, quoting here:您可以访问在第 3 段中也突出显示相同内容的 wiki,在此处引用:

In addition, the term "CSV" also denotes some closely related delimiter-separated formats that use different field delimiters, for example, semicolons.此外,术语“CSV”还表示一些密切相关的分隔符分隔格式,它们使用不同的字段分隔符,例如分号。 These include tab-separated values and space-separated values.这些包括制表符分隔的值和空格分隔的值。 A delimiter that is not present in the field data (such as tab) keeps the format parsing simple.字段数据中不存在的分隔符(例如制表符)使格式解析保持简单。 These alternate delimiter-separated files are often even given a.csv extension despite the use of a non-comma field separator.尽管使用了非逗号字段分隔符,但这些替代分隔符分隔的文件通常甚至被赋予 .csv 扩展名。 This loose terminology can cause problems in data exchange.这种松散的术语可能会导致数据交换出现问题。 Many applications that accept CSV files have options to select the delimiter character and the quotation character.许多接受 CSV 文件的应用程序都有 select 分隔符和引号字符的选项。 Semicolons are often used in some European countries, such as Italy, instead of commas.在一些欧洲国家,如意大利,通常使用分号而不是逗号。

https://en.wikipedia.org/wiki/Comma-separated_values https://en.wikipedia.org/wiki/Comma-separated_values

Now answering the question of @Ego:现在回答@Ego的问题:

  1. Incase you want to show in the same format while executing the bash file: echo "$(cat testfile.csv)"如果您想在执行 bash 文件时以相同的格式显示: echo "$(cat testfile.csv)"

  2. Incase you want to store it in array using bash script:如果您想使用 bash 脚本将其存储在数组中:

index=0
while IFS= read -r line; do
    testarray["$index"]="$line"
    index=$((index + 1));
done < testfile.csv

Print each line.打印每一行。 In this case, each line is stored as an item in an array.在这种情况下,每一行都存储为数组中的一个项目。

for eachline in "${testarray[@]}"
  do
    echo "$eachline"
  done

Instead of echo, you can perform some action on the individual line.您可以在单独的行上执行一些操作,而不是 echo。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM