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

rag*_*zor 4 bash

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

$ echo $'one&some text\ntwo&other text' | ./my_script.sh --delimiter &
Line:
1st: one
2nd: some tex
Line:
1st: two
2nd: other text
Run Code Online (Sandbox Code Playgroud)

也可以使用默认分隔符来调用,即\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
Run Code Online (Sandbox Code Playgroud)

use*_*001 6

您可以在 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
Run Code Online (Sandbox Code Playgroud)

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