2

I have a file:

AWK question about the example

This command that works well:

awk  '{ gsub(/...../, "&\n" ) ; print}' file
AWK q
uesti
on ab
out t
he ex
ample

Why this command does not print the same result?

awk  '{ gsub(/.{5}/, "&\n" ) ; print}' file
AWK question about the example

Why this command does not print the same result?

awk -v WIDTH=5 '{ gsub(".{"WIDTH"}", "&\n"); print }' file
AWK question about the example
Tedee12345
  • 1,182
  • 4
  • 16
  • 26

2 Answers2

7

To use {5} you need to enable re-interval like this:

awk --re-interval '{ gsub(/.{5}/, "&\n" ) ; print}' file
awk -v WIDTH=5 --re-interval '{ gsub(".{"WIDTH"}", "&\n"); print }' file

You could also use --posix too, but it will disable other functions in awk

awk -v WIDTH=5 --posix '{ gsub(".{"WIDTH"}", "&\n"); print }' file
Jotne
  • 40,548
  • 12
  • 51
  • 55
  • +1 Also, if you upgrade to Gnu Awk version 4, there is no need to specify `--re-interval` any longer.. – Håkon Hægland Jan 24 '14 at 09:49
  • Good point, but it would then be less portable, since most linux distro still is on gawk 3.xx. Do not ask me why since 4.x has been around for some time. – Jotne Jan 24 '14 at 09:54
  • 2
    You should state that `--re-interval` is the right solution, not `--posix` since though both will enable RE intervals the latter will disable all other useful gawk functionality, e.g. `gensub()`. – Ed Morton Jan 24 '14 at 15:05
  • 1
    @EdMorton Thanks for input, I have updated my answer to reflect this. – Jotne Jan 24 '14 at 15:36
5

You can use the fold command instead of awk:

fold -w 5 input

or if you don't have the input in a file:

echo 'AWK question about the example' | fold -w 5

Both Give:

AWK q
uesti
on ab
out t
he ex
ample
perreal
  • 94,503
  • 21
  • 155
  • 181