LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Another easy Bourne Shell Scripting question (https://www.linuxquestions.org/questions/programming-9/another-easy-bourne-shell-scripting-question-225583/)

WinterSt 09-02-2004 03:07 AM

Another easy Bourne Shell Scripting question
 
It is very simple this time (but not simple enough for me). I have file with data entries seperated by ",".
The files looks like this..
Code:

Anderson,Sarah,02-95437869
Brown,Sarah,02-99893878
Couch,David,02-95673456
Jones,Sarah,02-95671660
Smith,John,02-93272658
Williams,Nick,02-98781987

I want to display it with each field placed into left justified columns.
Code:

Anderson(white space)Sarah(white space)02-95437869
Brown(white space''')Sarah(white space)02-99893878
Couch(white space''')David(white space)02-95673456
Jones(white space''')Sarah(white space)02-95671660
Smith(white space''')John(white space')02-93272658
Williams(white space)Nick(white space')02-98781987


I thought that I would be able to do this by adding multiple \t between each field, but the command I thought would do it, doesn't work.
cat records.txt | tr "[,]" "[\t*2]"

It only replaces the "," with one "\t".


What could I try to do to display this data in columns, or perhaps a way to add multiple tabs?

P.S has to work in bourne shell (#!/bin/sh).

thanksgsg

Tinkster 09-02-2004 03:50 AM

Another easy homework-question? :)

itsme86 09-02-2004 03:59 AM

This one works for me:
Code:

#!/bin/sh

cat records.txt | sed 's/,/        /g'

That big space in there is where you shoud press the TAB key however many times you want.

jlliagre 09-02-2004 04:09 AM

However, it doesn't aligns well when fields have too distinct width.

Here's a try:
Code:

#!/bin/sh
awk -F, '
function format(s)
{
        padding="";
        l=length(s);
        while(l<22)
        {
                padding=padding " ";
                l++;
        }
        return(s padding);
}
{
        printf("%s %s %s\n",format($1),format($2),$3);
}' $1


Tinkster 09-02-2004 04:17 AM

Quote:

#!/bin/sh

cat records.txt | sed 's/,/ /g'
That's ugly ;) and uses cat in excess ... how about?

Code:

awk -F, '{printf("%-10s%-10s%-10s\n", $1,$2,$3)}' records.txt
And if you make the 10's just one higher than the length
of the longest string in each column you don't have to
worry about potential breaks of the structure ...

Or this very simple approach :)
Code:

column -t -s, records.txt


Cheers,
Tink

jlliagre 09-02-2004 11:38 AM

You win !

tonyfreeman 09-02-2004 01:47 PM

Wow ... that column command is bloody brilliant!

WinterSt 09-02-2004 07:41 PM

Thank you everyone, and especially Tinkster, my bourne shell does not have the column program, but the awk command you listed worked perfectly.

Thanks!


All times are GMT -5. The time now is 11:06 PM.