Shell - 以逗号分隔的字符串打印值

Shell - 以逗号分隔的字符串打印值

我有一个 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脚本?

答案1

使用 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

答案2

$ 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索引来查找与数字匹配的单词。

答案3

假设输入文件最多只有三列,以下使用while-read循环从标准输入中读取逗号分隔的值,并以类似于您所显示的格式输出它们:

#!/bin/sh

while IFS=, read -r first second third
do
    printf 'Line %d:\n' "$(( ++n ))"
    ${first:+printf 'First:\t%s\n' "$first"}
    ${second:+printf 'Second:\t%s\n' "$second"}
    ${third:+printf 'Third:\t%s\n' "$third"}
done

参数扩展扩展${variable:+word}wordifvariable已设置且非空。printf如果相应的变量包含要打印的数据,则代码将使用它来执行输出。

对提供的数据进行测试:

$ ./script.sh <file
Line 1:
First:  abc
Second: def
Third:  ghi
Line 2:
First:  abc
Second: ghi
Line 3:
First:  def
Second: abc
Third:  ghi
Line 4:
First:  def
Second: abc
Line 5:
First:  abc
Second: def
Line 6:
First:  abc
Second: def
Third:  ghi

相关内容