for循环与变量bash

时间:2010-10-20 12:45:59

标签: linux bash unix scripting

假设我有一个具有值的变量:

#!/bin/sh
    MYVARIABLE="first,second,third"

    for vars in MYVARIABLE
    do 
    echo $vars
    done

上面的内容无法正常工作,但看起来很好,这应该打印first second third而不是,我打算在没有,任何消息的情况下进行打印?

4 个答案:

答案 0 :(得分:9)

使用IFS(输入字段分隔符),例如

#!/bin/sh
MYVARIABLE="first,second,third"
IFS=","

for vars in $MYVARIABLE
do 
  echo $vars
done

答案 1 :(得分:2)

MYVARIABLE="first,second,third"
IFS=","
set -- $MYVARIABLE
for i in ${@}; do echo $i; done

# you can also use an array in cases where you want to use the values later on
array=($@)
for i in ${!array[@]}; do echo ${array[i]}; done

答案 2 :(得分:2)

MYVARIABLE="first,second,third"

for vars in $(echo $MYVARIABLE | tr "," "\n")
do 
  echo $vars
done

或者如果您使用IFS,请不要忘记在完成后将IFS设置回原来的

MYVARIABLE="first,second,third"

OIFS=$IFS
IFS=","
for vars in $MYVARIABLE
do 
    echo $vars
done
IFS=$OIFS

答案 3 :(得分:2)

不确定您要对MYVARIABLE的内容做什么,或者您如何填写它,但处理CSV数据的一个非常好的选择是使用awk

如果要打印此变量:

echo $MYVARIABLE | awk 'BEGIN { RS="," }{ print $0 }'

如果您有一个CSV文件并且需要对数据执行计算/转换,那么您应该让awk获取文件,使用类似的方法:

awk 'BEGIN { FS="," ; OFS="\n" } { print $1,$2,$3 }' filename.csv
(这只是一种意识形态,与你的问题无关)