user2395215
user2395215

Reputation: 55

understanding SUB used in an AWK command

I need to understand how this command is working:

awk 'BEGIN{while(a++<30)s=s " "};{sub(/^.{6}/,"&" s)};l' myfile

I understand how the first part (the expression in the BEGIN{} section) creates a 30 character long string of spaces. But don't understand the second part (sub).

The sub adds the recently generated string "s" to the 6th column of 'myfile'. But the way I see the command, the search pattern /^.{6}/ should look for all lines that start with one character (.) and then {6} and replace those with space-added string!

Can you please help me to understand this better?

Upvotes: 3

Views: 324

Answers (2)

Bill Karwin
Bill Karwin

Reputation: 562368

It has nothing to do with the 6th column, and it's not looking for a literal {6}.

The curly braces mean "this many of the preceding pattern" (if you invoke GNU awk with --posix or --re-interval).

So this pattern:

/^.{6}/

Is equivalent to this:

/^....../

What it's doing is adding the string s after the first 6 characters, which may be any characters.

The following awk command would do something similar:

awk 'BEGIN{while(a++<30)s=s " "} {print substr($0, 1, 6) s substr($0, 7)}' myfile

Upvotes: 3

Ed Morton
Ed Morton

Reputation: 203645

See @BillKarwin's answer for what it's doing, and see the 2nd awk script below for the more concise way to do it:

$ cat file
abcdefghi

$ awk 'BEGIN{while(a++<30)s=s " "} {sub(/^.{6}/,"&" s)} 1' file
abcdef                              ghi

$ awk '{printf "%-36s%s\n",substr($0,1,6),substr($0,7)}' file
abcdef                              ghi

Upvotes: 2

Related Questions