Bob
Bob

Reputation: 59

How to display text file in columns using bashscript in unix?

I am making a bash script contact list system. This is what it prints out.

=================
Menu
=================

Enter 1 for Insert new contact
Enter 2 for Print current contact list
Enter 3 for Search contact list
Enter 4 for Exit

Enter your selection: 

For "1" it ask for name, email, and phone and stores them for variables then stores them in a text file.

case "$answer" in
1) echo -e "Enter in a new contact name: \c"
    read name
   echo -e "Enter in new contact email address: \c"
    read email
   echo -e "Enter in new contact phone number: \c"
    read phone
   echo "$name, $email, $phone" >> contacts.txt ;;

For 2 is where I am having trouble. I want to display the text in three columns so I can sort them by name, email, or phone number. This is my code for case 2.

2) cat contacts.txt ;;

Obviously it only spits out:

Test Name, [email protected], 123-123-1234
Blank Data, [email protected], 234-555-5555

I want it to read:

Name          Email          Phone
Test Name     [email protected]  123-123-1234
Blank Data    [email protected]   234-555-5555

How would I do that? And how would I be able to sort it later on?

Upvotes: 1

Views: 3033

Answers (2)

John1024
John1024

Reputation: 113814

$ cat contacts.txt 
Test Name, [email protected], 123-123-1234
Blank Data, [email protected], 234-555-5555
$ awk -F, 'BEGIN{printf "%-12s %-15s %-12s\n","Name"," Email"," Phone"} {printf "%-12s %-15s %-12s\n",$1,$2,$3}' contacts.txt
Name          Email           Phone      
Test Name     [email protected]   123-123-1234
Blank Data    [email protected]    234-555-5555

How it works:

The printf statement allows custom formatting of output. Above the format string %-12s %-15s %-12s\n was used. Taking %-12s, for example, the 12s part means that we want to format a string to a width of 12 columns. The minus sign means that we want that field left-justified.

Looking at each piece of the awk code separately:

  • -F,

    This tells awk to use a comma as the field separator on each line.

  • BEGIN{printf "%-12s %-15s %-12s\n","Name"," Email"," Phone"}

    The BEGIN block is executed before the first line of the file is read. It is used here to print the header.

  • printf "%-12s %-15s %-12s\n",$1,$2,$3

    awk implicitly loops through every line in the file. For each line, we print out the first three fields as per the format statement.

Upvotes: 1

Cyrus
Cyrus

Reputation: 88563

Change

echo "$name, $email, $phone" >> contacts.txt ;;

to

echo "$name,$email,$phone" >> contacts.txt ;;

and try this:

(echo Name,Email,Phone; cat contacts.txt) | column -s , -t

Upvotes: 1

Related Questions