4

In the gawk manual, I found two functions patsplit and split.

  • I am wondering what their differences are?

  • I understand the purpose of split, but what is the purpose of patsplit?

Thanks.

2 Answers 2

8

In split, you supply a separator; whereas in patsplit you match a pattern between separators:

$ echo 'foo,bar' | awk '{n = split($0,a,/,/); for(i=1;i<=n;i++) print a[i]}'
foo
bar

whereas

$ echo 'foo,bar' | awk '{n = patsplit($0,a,/[^,]*/); for(i=1;i<=n;i++) print a[i]}'
foo
bar
1
  • I happened on your answer and appreciated the usage of each but found it unclear for split and cross referenced it with the documentation. It would be more helpful if you used more clear name for the parameters. This is also kinda old so here is what helped me. split(string, array [, fieldsep [, seps ] ]) as example: split("cul-de-sac", a, "-", seps) your example: string = $0 array = a fieldsep = / seps = / <-- this was the confusing part for me? gnu.org/software/gawk/manual/html_node/String-Functions.html explains both. Commented Jun 25, 2018 at 2:29
2

split matches the default field split, using FS (or a specific regular expression if specified): it uses a regular expression to match field separators. If you specify FS=,, then fields will be split by separating commas — the commas themselves won’t end up in the field contents, they’ll end up in the separators array (if specified).

patsplit matches the field pattern split, which can be used instead of the default field split by giving a value for FPAT: it uses a regular expression to match field contents. For example, if you’re only interested in the numbers given in any record, you could specify FPAT="[[:digit:].]+" or use patsplit with that regular expression to match all contiguous sets of digits, and manipulate those as fields.

8
  • 1
    Thanks. What does pat in patsplit stand for?
    – Tim
    Commented Jul 18, 2017 at 16:47
  • 1
    “pattern”, as in “pattern split”. Commented Jul 18, 2017 at 16:50
  • Thanks. I guess it is misnamed, because split also uses patterns although for separators. What does "FPAT" stand for? "field pattern"?
    – Tim
    Commented Jul 18, 2017 at 16:56
  • Yes, FPAT stands for “field pattern”. Commented Jul 18, 2017 at 17:19
  • 1
    @Tim - no, not really, though at first glance they might seem redundant. FPAT & patsplit were added to gnu awk so as to be able to define fields by content. Commented Jul 18, 2017 at 21:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .