【问题标题】:split for words separated with semicolonsplit 用于用分号分隔的单词
【发布时间】:2011-12-21 11:53:24
【问题描述】:

我有一些类似的字符串

1;2;3;4;5

我希望能够逐个遍历这个字符串。第一次迭代取 1,下一次取 2,最后 5 次。

我想要这样的东西

for i in $(myVar)
do
echo $i
done

但我不知道如何填写 myvar

【问题讨论】:

    标签: linux bash shell terminal


    【解决方案1】:

    如果您只为单个命令分配 IFS 变量,则无需备份它:

    $ IFS=';' read -a words <<<"1;2;3;4;5"
    $ for word in "${words[@]}"
    do
        echo "$word"
    done
    1
    2
    3
    4
    5
    

    其他有用的语法:

    $ echo "${words[0]}"
    1
    $ echo "${words[@]: -1}"
    5
    $ echo "${words[@]}"
    1 2 3 4 5
    

    【讨论】:

      【解决方案2】:

      可能最简单的方法是更改​​IFS 环境变量:

      OLDIFS="$IFS"
      IFS=';'
      for num in $a; do echo $num; done
      
      # prints:
      1
      2
      3
      4
      5
      
      IFS="$OLDIFS"
      

      记得之后再改回来,否则会发生奇怪的事情! :)

      来自 bash 手册页:

         IFS    The Internal Field Separator that is  used  for  word  splitting
                after  expansion  and  to  split  lines into words with the read
                builtin  command.   The  default  value  is  ``<space><tab><new-
                line>''.
      

      【讨论】:

      • 或者你可以在子shell中运行:) ... (IFS=';'; for num in $a; do echo $num; done)
      【解决方案3】:
      echo '1;2;3;4;5' | tr \; \\n | while read line ; do echo $line; done
      

      【讨论】:

        【解决方案4】:

        这可能对你有用:

        array=($(sed 'y/;/ /' <<<"1;2;3;4;5"))
        for word in "${array[@]}"; do echo "$word"; done
        

        【讨论】:

          猜你喜欢
          • 2021-02-09
          • 2014-03-31
          • 1970-01-01
          • 1970-01-01
          • 2011-12-14
          • 2017-09-19
          • 1970-01-01
          • 2019-01-24
          • 1970-01-01
          相关资源
          最近更新 更多