[英]bash (awk) split string
I have a string: 我有一个字符串:
b="123 321 || 431543 653 || 039 ||"
I use " || " as separator. 我使用“ ||”作为分隔符。 I want to separate it in 3 strings:
我想将其分成3个字符串:
123 321
431543 653
039 ||
When I try to split it with bash: 当我尝试用bash拆分它时:
for element in ${b//" || "/ } ; do echo $element; done
The result: 结果:
123
321
431543
653
039
||
When I use awk - I have same result (I get only the first number, but result is expected to be "123 321"): 当我使用awk时-我得到相同的结果(我只得到第一个数字,但结果应该是“ 123 321”):
echo $b |awk '{split($0,a," || "); print a[1]}'
123
you need to escape pipe char 你需要逃脱管道字符
$ awk -v b="123 321 || 431543 653 || 039 ||" 'BEGIN{print split(b,a," \\|\\| ")}'
3
note that size is not 4 but 3, since the last delimiter is missing the trailing space char. 请注意,大小不是4,而是3,因为最后一个定界符缺少尾随空格char。 Perhaps you should make the wrapping space chars optional.
也许您应该使包装空格为可选。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.