Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex with awk or gawk

Tags:

regex

awk

gawk

I'm a beginner user of awk/gawk. If I run below, the shell gives me nothing. Please help!

echo "A=1,B=2,3,C=,D=5,6,E=7,8,9"|awk 'BEGIN{
n = split($0, arr, /,(?=\\w+=)/)
for (x=1; x<n; x++) printf "arr[%d]=%s\n", x, arr[x]
}'

.....................................................

I am trying to parse:

A=1,B=2,3,C=,D=5,6,E=7,8,9

Expected Output:

A=1
B=2,3
C=
D=5,6
E=7,8,9

I bet there's something wrong with my awk.

like image 448
Jaeh Avatar asked Dec 20 '22 10:12

Jaeh


2 Answers

gawk doesn't support look-ahead.

if you want gawk to parse it as you expected, try this:

awk '{n=split(gensub(/,([A-Z])/, " \\1","g" ),arr," ");for(x=1;x<=n;x++)print arr[x]}'

test with your example:

kent$  echo "A=1,B=2,3,C=,D=5,6,E=7,8,9"|awk '{n=split(gensub(/,([A-Z])/, " \\1","g" ),arr," ");for(x=1;x<=n;x++)print arr[x]}'
A=1
B=2,3
C=
D=5,6
E=7,8,9
like image 195
Kent Avatar answered Jan 04 '23 19:01

Kent


This might be easier with sed:

$ echo "A=1,B=2,3,C=,D=5,6,E=7,8,9" | sed 's/,\(\w\+=\)/\n\1/g'
A=1
B=2,3
C=
D=5,6
E=7,8,9
like image 32
Andrew Clark Avatar answered Jan 04 '23 17:01

Andrew Clark