【问题标题】:Split words with commas and replace character instead of null in bash在bash中用逗号分割单词并替换字符而不是null
【发布时间】:2014-03-12 19:17:55
【问题描述】:

您好,我想用逗号分隔单词并在 bash 中替换 0 字符而不是 null。

例如; hello,world,,abc,234,,41,1

可能是 =>

hello  
world   
0  
abc  
234  
0  
41  
1

我该怎么做?感谢您的建议。

【问题讨论】:

    标签: linux bash null split


    【解决方案1】:

    使用 awk

    s='hello,world,,abc,234,,41,1'
    awk -F, '{for (i=1; i<=NF; i++) print $i?$i:0}' <<< "$s"
    hello
    world
    0
    abc
    234
    0
    41
    1
    

    【讨论】:

      【解决方案2】:

      好的,我这里是纯 bash 4 的示例 :)

      #!/bin/bash
      
      s='hello,world,,abc,234,,41,1'
      IFS=","
      for i in $s; do
       if [ -z $i ]; then echo 0; else echo $i; fi
      done
      

      输出:

      /usr/tmp $ ./1
      hello
      world
      0
      abc
      234
      0
      41
      1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-30
        • 2014-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多