Print strings that match pattern with awk

I have a file with many lines which contain strings like [46ms] [986976ms] .. etc.
But with no rule regarding field separators or anything else.
I want to print ONLY THE STRING from each line , not the entire line !!!

For example from the lines :

Flow [login] on service [credentialService] executed with success in [46ms]. Performances are []
[] Flow [login] on service [exposerService] executed with success in [6406ms]. Performances are [] 
Flow [logout] on [service] [credentialService] executed with error in [34512ms]. Performances are [] and []

I want to have the output :

[46ms]
[6406ms]
[34512ms]

Or even better only the numbers from each of these strings. I want it with awk because I need speed, I have very big files to work with.

thanks!

as per your input..

this work fine. If not please provide some more variations from your input file..:slight_smile:

awk -F "[][]" '{ for(i=2;i<=NF;i+=2){if($i ~ /^[0-9]/){print "["$i"]"}}}' file
1 Like

Hello, yes it is what I wanted. Just one more little thing. Is it possible to print only the digits from each of the matched strings ? I mean without square brackets and the word "ms" ?

I know I can extract them with a sed afterwards or something else, but I think your awk snippet can provide that directly.

thanks again !

Yes we can do this with awk..:slight_smile:

awk -F "[][]" '{ for(i=2;i<=NF;i+=2){if($i ~ /^[0-9]/){gsub("ms","",$i); print $i}}}' file

With some sane input:

awk 'sub(/].*/,"")&&/^[0-9]/{print $0+0}' RS='[' file
1 Like

Good stuff . I've got what I need.

Cheers !

---------- Post updated at 07:42 AM ---------- Previous update was at 07:36 AM ----------

Hi, yes, it is even faster ! :

$: time zcat log.gz | grep "executed with .* in \[.*\]" | awk 'sub(/].*/,"")&&/^[0-9]/{print $0+0}' RS='[' | wc -l
31675

real    0m3.719s
user    0m4.068s
sys     0m0.164s
$:
$: time zcat log.gz | grep "executed with .* in \[.*\]" | awk -F "[][]" '{ for(i=2;i<=NF;i+=2){if($i ~ /^[0-9]/){gsub("ms","",$i); print $i}}}' | wc -l
31675

real    0m5.468s
user    0m5.741s
sys     0m0.163s