Question

Given the following input:

check1;check2
check1;;check2
check1,check2

and the awk command:

awk -F';+|,' '{print $1 FS $2}'

FS should contain the selected delimiter?

How can you print the delimiter which is selected i.e. either of ;, ;; or , not the regular expression that the describes the delimiters.

If the input is check1;check2 then the output should be check1;check2.

Was it helpful?

Solution 2

I don't think awk stores the matched delimiter anywhere. If you use GNU awk, you can do it yourself:

gawk '{match($0, /([^;,]*)(;+|,)(.*)/, a); print a[1], a[2], a[3]}'

OTHER TIPS

If you're using GNU Awk (gawk) you can use the 4th argument of split():

gawk '{split($0, a, /;+|,/, seps); print a[1] seps[1] a[2]}' file

Output:

check1;check2
check1;;check2
check1,check2

Using it within a loop is also easy to handle:

gawk '{nf = split($0, a, /;+|,/, seps); for (i = 1; i <= nf; ++i) printf "%s%s", a[i], seps[i]; print ""}' file

22011,25029;;3331,25275
6740,16516;;27292,1217
13480,31488;;7947,18804
328,30623;;12470,6883

If you only need the fields you would only have to touch a. Separators would be separated in seps and the indices of those are aligned with a.

GNU awk has this feature for records not fields so you could also do something like this:

$ awk '{printf "%s%s",$0,RT}' RS=';+|,|\n' file
check1;check2
check1;;check2
check1,check2

Where RT is the value match by RS for the given record which you can see by:

$ awk '{printf "%s",RT}' RS=';+|,|\n' file
;
;;
,
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top