如何读取bash中的行并用指定的分隔符分隔它们?

时间:2015-09-07 12:24:21

标签: bash

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

$ 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

输出应与上述相同。

脚本应通过标准输入。

最简单的方法是什么?可能是纯粹的打击。

我尝试过这种方法,但它不起作用,我不知道原因:

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

2 个答案:

答案 0 :(得分:2)

拯救......

 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

答案 1 :(得分: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

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