On 2013-11-20 00:16, Mike Miller wrote:
> On Tue, 19 Nov 2013, Kathryn Hogg wrote:
> 
>> If you want to print out the whole row with field #6 modified, try 
>> this
>> 
>> awk -F';' 'BEGIN { OFS=";"}
>> {$6=substr($6, 0, 3); print $0;}'
> 
> 
> Wow.  I love it.  I had no idea that I could do things like that with
> awk. The big revelation for me is that I can change a value in a field
> and then print out the line with that change.  That is really good to
> know.
> 
> I'm not sure what BEGIN does -- is it needed?  Same for the final
> semicolon.  I dropped them and it seemed to do the same thing:

In awk, each statement is

pattern statement

where pattern defines which lines the statements are applied to.

BEGIN is a special pattern that is applied once before any lines are 
read.  My second line doesn't have a pattern so its applied to all 
lines.

> 
> echo "a;2; 3;4;5 ;abcdefghijk;7;8;9" | awk -F';' 'BEGIN { OFS=";"}
> {$6=substr($6, 0, 3); print $0;}'
> a;2; 3;4;5 ;abc;7;8;9
> 
> echo "a;2; 3;4;5 ;abcdefghijk;7;8;9" | awk -F';' '{OFS=";"}
> {$6=substr($6, 0, 3); print $0}'
> a;2; 3;4;5 ;abc;7;8;9

The difference here is that in the first case, OFS is set exactly once 
at the beginning of the script.  In the second, OFS is set for every 
line that is read from the file.  Its a bit wasteful but not too bad.

> I didn't know substr() either, which is a good one.  I would have
> thought to use printf() but that is not nearly as good.



-- 
Kathryn Hogg
http://womensfooty.com