The UNIX and Linux Forums  
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #3 (permalink)  
Old 05-30-2007
bakunin bakunin is offline Forum Staff  
Bughunter Extraordinaire
  
 

Join Date: May 2005
Location: In the leftmost byte of /dev/kmem
Posts: 1,628
As the "fields" in your file are separated by a constant char ("|") use cut to separate them, then print the lines via printf (i assume Kornshell here, use 'echo' instead of 'print' if you are using something else):

Code:
cat infile | while read line ; do
     # split each input line to fields and catch these in variables
     field1="$(print - "$line" | cut -d'|' -f1)"
     field2="$(print - "$line" | cut -d'|' -f2)"
     field3="$(print - "$line" | cut -d'|' -f3)"
     .....
     
     # after you are done with the line print it out again
     # i assume here that the first column should be 20 chars wide, the next
     # two 15, and so on. see the second example below.
     printf '%20s %15s %15s [...]\n' "$field1" "field2" "$field3" [...] >> outfile
done
This is using (a fixed number of) fixed-width columns and you have to know the widths in advance. It is possible to create dynamically formatted columns but you will have to read the infile two times:


Code:
maxlength1=0
maxlength2=0
....
cat infile | while read line ; do
     # in the first run we split and get the max width for each column
     field1="$(print - "$line" | cut -d'|' -f1)"
     length1=$(print - "$field1" | wc -c)
     if [ $length1 -gt $maxlength1 ] ; then
          maxlength1=$length1
     fi
     field2="$(print - "$line" | cut -d'|' -f2)"
     length2=$(print - "$field2" | wc -c)
     if [ $length2 -gt $maxlength2 ] ; then
          maxlength2=$length1
     fi
     .....
done

# put together the output template for printf
template='%'"$maxlength1"'s   %"'$maxlength2"'s [.....]\n'
   
cat infile | while read line ; do
     # in the second run we split again and print using the found widths
     field1="$(print - "$line" | cut -d'|' -f1)"
     field2="$(print - "$line" | cut -d'|' -f2)"
     ....
     printf "$template" "$field1" "field2" "$field3" [...] >> outfile
done
I'd suggest you use (dynamical) arrays instead the numbered variables to make the script able to deal with a variable number of fields in the input file as a further enhancement. The column separator could then be provided as a parameter making the script as widely usable as possible.

bakunin