Home > Enterprise >  How to split on several delimiters but keep those in between square brackets?
How to split on several delimiters but keep those in between square brackets?

Time:10-01

I am trying to split the following text string by dash, square brackets and colon delimiters but keep those in square brackets

Input:

10:100 - [10/09/21:12:23:22] 

Desired output:

100, 10/09/21:12:23:22

My current code:

awk -F '[- ":]' '{print $1, $2, $3, $4, $5}'

CodePudding user response:

1st solution: With GNU awk you could try following code.

awk '
match($0,/:([^[:space:]] )[[:space:]] -[[:space:]] \[([^]]*)\]/,arr){
   print arr[1],arr[2]
}
' Input_file

2nd solution: Using sed's s(substitution operation) along with its capturing group capability try following:

sed -E 's/^[^:]*:([^[:space:]] )[[:space:]] -[[:space:]] \[([^]]*)\]/\1 \2/'  Input_file

3rd solution: Using any awk you could use following code. Using its sub and gsub operations on 1st and last fields.

awk '{sub(/.*:/,"",$1);gsub(/^\[|\]$/,"",$NF);print $1,$NF}' Input_file

4th solution: With Perl's one-liner solution using a lazy match.*? one could try following using its substitution operation.

perl -pe 's/^.*?:([^[:space:]] )[[:space:]] -[[:space:]] \[([^]]*)\]/\1 \2/'  Input_file
  • Related