【问题标题】:How to read lines in bash and delimit them by a specified delimiter? [duplicate]如何读取 bash 中的行并用指定的分隔符分隔它们? [复制]
【发布时间】:2015-12-03 00:17:19
【问题描述】:

我需要编写一个具有以下行为的脚本:

$ echo $'one&some text\ntwo&other text' | ./my_script.sh --delimiter &
Line:
1st: one
2nd: some tex
Line:
1st: two
2nd: other text

也可以使用默认分隔符\t

$ echo $'one\tsome text\nfive\tother text' | ./my_script.sh

输出应该和上面一样。

脚本应该通过标准输入接受输入。

最简单的方法是什么?可能在纯 bash 中。

我尝试过这种方法,但它不起作用,我不知道为什么:

while read -r line
do
    echo "$line"
    IFS=$DELIMITER
    arr=(${line//$DELIMITER/ })
    echo ${arr[0]}
    echo ${arr[1]}
done

【问题讨论】:

    标签: bash


    【解决方案1】:

    求救...

     echo -e "one&some text\ntwo&other text" | awk 
         `BEGIN {
             n=spit("st,nd,rd,th",s,",")
          } 
          {  print "Line: "; 
             c=split($0,r,"&");  
             for(i=1;i<=c;i++) 
                 print i s[(i%10)%n] ": " r[i]
          }
    

    会给

    Line: 
    1st: one
    2nd: some text
    Line: 
    1st: two
    2nd: other text
    

    请注意,这个简单的后缀查找将分解为 11-13

    【讨论】:

      【解决方案2】:

      您可以在 bash 中完成此操作,而无需使用外部程序。

      $ cat script.sh
      #!/bin/bash
      if [ "$1" = "--delimiter" ]
      then
        d=$2
      else 
        d=$'\t'
      fi
      
      while IFS="$d" read -r first rest; do
        echo "1st: $first"
        echo "2nd: $rest"
      done 
      $ echo $'one\tsome text\nfive\tother text' | ./script.sh
      1st: one
      2nd: some text
      1st: five
      2nd: other text
      $ echo $'one&some text\nfive&other text' | ./script.sh --delimiter \&
      1st: one
      2nd: some text
      1st: five
      2nd: other text
      

      请注意,与符号必须转义(或引用),否则它将在后台执行命令。

      【讨论】:

        猜你喜欢
        • 2023-04-11
        • 2012-03-22
        • 1970-01-01
        • 2013-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多