简体   繁体   中英

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:

123 321
431543 653
039 ||

When I try to split it with 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"):

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. Perhaps you should make the wrapping space chars optional.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM