Register
It is currently Thu Nov 20, 2014 4:51 pm

Formatting contents of file


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Tue Aug 24, 2010 1:28 pm   

Joined: Tue Aug 24, 2010 1:15 pm
Posts: 1
So I have a file like so:
Code:
4: 7:.2:
6: 7:.2:
10: 7:.2:
12: 7:.2:
dist: 7:.2:
price_break_id1:  9:.0:
price_break_id2:  9:.0:
price_break_id4:  9:.0:
price_break_id6:  9:.0:
price_break_id10:  9:.0:
price_break_id12:  9:.0:
price_break_iddist:  9:.0:
2: 7:.2:


I want the file to be formatted to have the colons 'right aligned' with regards to the colons.
Code:
                 4:  7:.2:
                 6:  7:.2:
                10:  7:.2:
                12:  7:.2:
              dist:  7:.2:
   price_break_id1:  9:.0:
   price_break_id2:  9:.0:
   price_break_id4:  9:.0:
   price_break_id6:  9:.0:
  price_break_id10:  9:.0:
  price_break_id12:  9:.0:
price_break_iddist:  9:.0:
                 2:  7:.2:


I am using sco unix mp4
(which means i can use printf)


Top
 Profile  
 PostPosted: Tue Aug 24, 2010 3:01 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 567
Code:
inputfile=dunpealslyr.in
maxLength=$(awk -F: '{ if (x < length($1)) x = length($1) } END { print x }'  $inputfile)
while IFS=: read one two three; do printf '%'$maxLength's:%3s:%s:\n' "$one" "$two" "$three"; done < $inputfile
                 4:  7:.2:
                 6:  7:.2:
                10:  7:.2:
                12:  7:.2:
              dist:  7:.2:
   price_break_id1:  9:.0:
   price_break_id2:  9:.0:
   price_break_id4:  9:.0:
   price_break_id6:  9:.0:
  price_break_id10:  9:.0:
  price_break_id12:  9:.0:
price_break_iddist:  9:.0:
                 2:  7:.2:
awk should be able to do it all by itself, but I don't know how :(


Top
 Profile  
 PostPosted: Tue Aug 24, 2010 4:12 pm   
User avatar

Joined: Sun Jun 27, 2010 12:57 am
Posts: 192
Code:
awk -F: 'NR==FNR { l=length($1); max=(l>max)?l:max; next; } { printf("%"max"s:%3s:%s:\n", $1,$2,$3); }' input.txt input.txt


Remember to put the input file twice at the end, awk will parse the same file twice. First run finding the maximum length of the first column (and not printing because of the 'next'). Second run just printing the output with the maximum column length.


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: Google [Bot] and 4 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP