1819696 Members
3571 Online
109605 Solutions
New Discussion юеВ

awk and prinf

 
gsudha
New Member

awk and prinf

Hi,
I am replacing the 4th feild of an input line and then formatting the input line using printf

Here is my code:
Line="# IN01379 Larry 2010/03/17 (should be the same as FIW-LR AM)"
REPL_DT=`date +'%Y\/%m\/%d'`
REP_LINE=$(echo $Line | awk -v var=$REPL_DT '{$4=var; print}')
NEW_LINE=$(echo $REP_LINE | awk '{printf "# %-7s %9s %16s\n", $2,$3,$4}')

The problem here is, since I am formatting only till $4 in prinf statement, anything that comes after the 4 feild is not printed. The number of feilds/words that comes after 4th feild is not fixed.

I do not have to format the feilds after $4. But I have to format the first four feilds as shown above.

Any way to format only the first 4 feilds of the input line and retain the rest of line.

3 REPLIES 3
Dennis Handly
Acclaimed Contributor

Re: awk and printf

>Anyway to format only the first 4 fields of the input line and retain the rest of line

You could use a for-loop to print the rest of the fields:
for (i=5; i <=NF; ++i)
printf " %s", $I
print ""

James R. Ferguson
Acclaimed Contributor

Re: awk and prinf

Hi:

Another way is to use Perl and do something like:

# echo "abc def ghi jkl xxx yyy zzz"|perl -nae '{printf "# %-7s %9s %16s %s\n",@F[1..3],"@F[4..@F]"}'

Perl counts zero-relative whereas 'awk' counts from one.

Regards!

...JRF...
gsudha
New Member

Re: awk and prinf

Thank you very much. Your solution using perl works. The below code, using awk with substr and index also works:

echo "hi hello how are you doing" | awk '{printf "# %-7s %9s %16s %s\n", $2,$3,$4,substr($0,index($0,$5))}'