Linux

Shell - 以逗號分隔的字元串列印值

  • November 26, 2018

我有一個帶有逗號分隔值的 txt 文件。

cat file.txt

abc,def,ghi
abc,ghi
def,abc,ghi
def,abc
abc,def
abc,def,ghi

我想while do read line from file用逗號分隔列印這些值。

例如:

expecting output for Line no 1:
first col=abc
second col=def
third col=ghi
expecting output for Line no 2:
first col=abc
second col=ghi

如果該行具有三個值,則應列印讀取行

first col=value
second col=value
third col=value

別的

first col=value
second col=value

如何創建這個 shell 腳本?

$ awk -F, '{ print "line " NR; for (i=1;i<=NF;i++) { print "Col " i "="$i } }' input
line 1
Col 1=abc
Col 2=def
Col 3=ghi
line 2
Col 1=abc
Col 2=ghi
line 3
Col 1=def
Col 2=abc
Col 3=ghi
line 4
Col 1=def
Col 2=abc
line 5
Col 1=abc
Col 2=def
line 6
Col 1=abc
Col 2=def
Col 3=ghi

如果您真的想從數字列音譯為“第一”、“第二”等,您可以定義一個數組並i用作索引來查找與數字匹配的單詞。

使用 bash 你可以做

ordinals=( first second third fourth fifth sixth )
n=0
while IFS=, read -ra cols; do
   echo "line $((++n))"
   for i in "${!cols[@]}"; do
       echo "${ordinals[i]} col=${cols[i]}"
   done
done < file

它將每行中的單詞讀入一個名為 的數組cols,然後我們對該數組的索引進行互動,以便我們可以將值與序數相關聯。

對於前 3 行,我們得到

line 1
first col=abc
second col=def
third col=ghi
line 2
first col=abc
second col=ghi
line 3
first col=def
second col=abc
third col=ghi

引用自:https://unix.stackexchange.com/questions/484264