我正在嘗試根據標題動態地從 CSV 檔案中讀取值。這是我的輸入檔案的樣子。
File 1:
name,city,age
john,New York,20
jane,London,30
要么
File 2:
name,age,city,country
john,20,New York,USA
jane,30,London,England
我可能沒有遵循完成此任務的最佳方法,但我嘗試了以下代碼。
#!/bin/bash
{
read -r line
line=`tr ',' ' ' <<< $line`
while IFS=, read -r `$line`
do
echo $name
echo $city
echo $age
done
} < file.txt
我期待上面的代碼將標頭的值作為變數名讀取。我知道輸入檔案的列順序可能不同。但是,我希望這些檔案在輸入檔案中有名稱、城市和年齡列。這是正確的方法嗎?如果是這樣,如果失敗并出現錯誤 - “line7: name: command not found”,上述代碼的修復方法是什么。
uj5u.com熱心網友回復:
該問題是由反引號引起的。Bash 將評估內容并將反引號替換為其剛剛評估的命令的輸出。
您可以簡單地在讀取命令之后使用變數來實作您想要的:
#!/bin/bash
{
read -r line
line=`tr ',' ' ' <<< $line`
echo "$line"
while IFS=, read -r $line ; do
echo "person: $name -- $city -- $age"
done
} < file.txt
關于您的代碼的一些注釋:
反引號語法是舊語法,現在首選用于
$(...)評估命令。新語法更加靈活。set -euo pipefail您可以使用(請參閱此處)啟用自動腳本失敗。如果遇到錯誤,這將使您的腳本停止。您的代碼目前對無效的標頭資料非常敏感:使用類似的檔案
n ame,age,city,country
john,20,New York,USA
jane,30,London,England
您的腳本(或者更確切地說是我答案開頭的版本)將運行沒有錯誤但輸出無效。
參考變數以防止不必要的拆分也是一種好習慣。
為了使其更加健壯,您可以按如下方式進行更改:
#!/bin/bash
set -euo pipefail
# -e and -o pipefail will make the script exit
# in case of command failure (or piped command failure)
# -u will exit in case a variable is undefined
# (in you case, if the header is invalid)
{
read -r line
readarray -d, -t header < <(printf "%s" "$line")
# using an array allows to detect if one of the header entries
# contains an invalid character
# the printf is needed because bash would add a newline to the
# command input if using heredoc (<<<).
while IFS=, read -r "${header[@]}" ; do
echo "$name"
echo "$city"
echo "$age"
done
} < file.txt
uj5u.com熱心網友回復:
awk在給定任一輸入檔案的情況下,稍微不同的方法可以讓處理所需輸出的欄位分離和排序。下面awk將所需的輸出順序存盤在規則f[]中設定的(欄位)陣列中BEGIN。然后在檔案 ( FNR==1) 的第一行洗掉陣列a[]并用當前檔案中的標題填充。此時,您只需在f[]陣列中按順序遍歷欄位名稱并從當前行輸出相應的欄位,例如
awk -F, '
BEGIN { f[1]="name"; f[2]="city"; f[3]="age" } # desired order
FNR==1 { # on first line read header
delete a # clear a array
for (i=1; i<=NF; i ) # loop over headings
a[$i] = i # index by heading, val is field no.
next # skip to next record
}
{
print "" # optional newline between outputs
for (i=1; i<=3; i ) # loop over desired field order
if (f[i] in a) # validate field in a array
print $a[f[i]] # output fields value
}
' file1 file2
示例使用/輸出
對于您在file1和中顯示的內容file2,您將擁有:
$ awk -F, '
> BEGIN { f[1]="name"; f[2]="city"; f[3]="age" } # desired order
> FNR==1 { # on first line read header
> delete a # clear a array
> for (i=1; i<=NF; i ) # loop over headings
> a[$i] = i # index by heading, val is field no.
> next # skip to next record
> }
> {
> print "" # optional newline between outputs
> for (i=1; i<=3; i ) # loop over desired field order
> if (f[i] in a) # validate field in a array
> print $a[f[i]] # output fields value
> }
> ' file1 file2
john
New York
20
jane
London
30
john
New York
20
jane
London
30
盡管具有不同的欄位順序,但兩個檔案的讀取和處理方式相同。如果您還有其他問題,請告訴我。
uj5u.com熱心網友回復:
如果使用 Bash 版本≥ 4.2,則可以使用關聯陣列來捕獲任意數量的欄位,并將其名稱作為鍵:
#!/usr/bin/env bash
# Associative array to store columns names as keys and and values
declare -A fields
# Array to store columns names with index
declare -a column_name
# Array to store row's values
declare -a line
# Commands block consuming CSV input
{
# Read first line to capture column names
IFS=, read -r -a column_name
# Proces records
while IFS=, read -r -a line; do
# Store column values to corresponding field name
for ((i=0; i<${#column_name[@]}; i )); do
# Fills fields' associative array
fields["${column_name[i]}"]="${line[i]}"
done
# Dump fields for debug|demo purpose
# Processing of each captured value could go there instead
declare -p fields
done
} < file.txt
檔案 1 的示例輸出
declare -A fields=([country]="USA" [city]="New York" [age]="20" [name]="john" )
declare -A fields=([country]="England" [city]="London" [age]="30" [name]="jane" )
對于較舊的 Bash 版本,沒有關聯陣列,也可以使用索引列名稱:
#!/usr/bin/env bash
# Array to store columns names with index
declare -a column_name
# Array to store values for a line
declare -a value
# Commands block consuming CSV input
{
# Read first line to capture column names
IFS=, read -r -a column_name
# Proces records
while IFS=, read -r -a value; do
# Print record separator
printf -- '--------------------------------------------------\n'
# Print captured field name and value
for ((i=0; i<"${#column_name[@]}"; i )); do
printf '%-18s: %s\n' "${column_name[i]}" "${value[i]}"
done
done
} < file.txt
輸出:
--------------------------------------------------
name : john
age : 20
city : New York
country : USA
--------------------------------------------------
name : jane
age : 30
city : London
country : England
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/432233.html
