0

我在 txt 文件中有几行字符串,如下所示:

输入.txt-->

abc;def;ghi jklm;mno pqr;
abcde;fgh;ijk lmno;pqrs tuv;

我的代码是这样的。它不适用于空间。请帮忙。

awk -F";" '{print $1,$2,$3,$4}' input.txt | while read var1    
var2 var3 var4 
Do
 echo 'var1 = ' $var1
 echo 'var2 = ' $var2
 echo 'var3 = ' $var3
 echo 'var4 = ' $var4
Done

所需的输出-->

var1 = abc
var2 = def
var3 = ghi jklm
var4 = mno pqr

var1 =abcde
var2 =fgh
var3 =ijk lmno
var4 =pqrs tuv
4

1 回答 1

4

这可以使它:

while IFS=';' read -r val1 val2 val3 val4
do
  echo "val1 = $val1"
  echo "val2 = $val2"
  echo "val3 = $val3"
  echo "val4 = $val4"
done < input.txt

要考虑的基本方面是IFS=";"定义输入字段分隔符。read -r val1 .. val4我们指出将定义哪些变量。

它可以更容易awk

$ awk -F";" '{for (i=1; i<NF; i++) {print "val"i,"=",$i}}' input.txt

它基本上定义;为带有-F ";". 然后使用 循环遍历所有这些字段for i并打印它们。NF表示字段的数量,并且循环最多,NF-1因此最后一个空的不显示。感谢 JS웃 的提示 :)

测试

$ while IFS=';' read -r val1 val2 val3 val4; do echo "val1 = $val1"; echo "val2 = $val2"; echo "val3 = $val3"; echo "val4 = $val4"; echo; done < a
val1 = abc
val2 = def
val3 = ghi jklm
val4 = mno pqr

val1 = abcde
val2 = fgh
val3 = ijk lmno
val4 = pqrs tuv

awk版本:

$ awk -F";" '{for (i=1; i<NF; i++) {print "val"i,"=",$i}}' a
val1 = abc
val2 = def
val3 = ghi jklm
val4 = mno pqr
val1 = abcde
val2 = fgh
val3 = ijk lmno
val4 = pqrs tuv
于 2013-07-19T11:32:01.713 回答