使用IFS进行Bash脚本编写

时间:2018-04-27 22:32:45

标签: bash ifs

我需要在Bash中使用IFS =','

./ test.sh Mike,Texas Nik,Toronto Lucas,Iowa

Hello Mike

你来自德克萨斯州

Hello Nik

你来自多伦多

Hello Lucas

你来自爱荷华州

#!/bin/bash
    IFS=',' read -r -a array <<< "$string"


    for index in "${!array[@]}"
    do
            echo Hello "$index ${array[index]}"
            echo You are from "$index ${array[index]}"
    done

3 个答案:

答案 0 :(得分:0)

您无需修改​​IFS内部字段分隔符),您需要参数展开并删除子字符串,例如

#!/bin/bash

for i in "$@"; do
    printf "Hello %s\nYou are from %s\n" "${i%,*}" "${i#*,}"
done

示例使用/输出

$ ./test.sh Mike,Texas Nik,Toronto Lucas,Iowa
Hello Mike
You are from Texas
Hello Nik
You are from Toronto
Hello Lucas
You are from Iowa

答案 1 :(得分:0)

您可以仅使用for argument循环参数 - 这将使用空格分隔的参数一次填充名为argument的变量。然后你可以读取以逗号分隔的值。例如:

set -- Mike,Texas Nik,Toronto Lucas,Iowa # For testing purposes
for argument
do
    IFS=, read name state <<< "$parameter"
    echo "Hello ${name}"
    echo "You are from ${state}"
done

答案 2 :(得分:-1)

根据我的看法,这是我的建议:

for i in $* ; do

     name=$(echo $i | awk -F, '{print $1}' )
     wherefrom=$(echo $i | awk -F, '{print $2'})

     echo Hello $name, you are from $wherefrom
done