How to read lines in bash and delimit them by a specified delimiter?
本问题已经有最佳答案,请猛点这里访问。
我需要写一个具有以下行为的脚本:
1 2 3 4 5 6 7 8 | $ echo $'one&some text two&other text' | ./my_script.sh --delimiter & Line: 1st: one 2nd: some tex Line: 1st: two 2nd: other text |
也可以使用默认分隔符
five\tother text' | ./my_script.sh
输出应与上述相同。
脚本应该通过标准输入。
最简单的方法是什么?可能是纯粹的狂欢。
我尝试过这种方法,但它不起作用,我不知道为什么:
1 2 3 4 5 6 7 8 | while read -r line do echo"$line" IFS=$DELIMITER arr=(${line//$DELIMITER/ }) echo ${arr[0]} echo ${arr[1]} done |
您可以在bash中完成,而不需要使用外部程序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | $ 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 five\tother text' | ./script.sh 1st: one 2nd: some text 1st: five 2nd: other text $ echo $'one&some text five&other text' | ./script.sh --delimiter \& 1st: one 2nd: some text 1st: five 2nd: other text |
请注意,必须转义(或引用)和号,否则它将在后台执行该命令。
害怕营救…
1 2 3 4 5 6 7 8 9 10 | echo -e"one&some text two&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] } |
将给予
1 2 3 4 5 6 | Line: 1st: one 2nd: some text Line: 1st: two 2nd: other text |
注意,这个简单的后缀查找将在11-13中分解