Monomoni
Monomoni

Reputation: 435

Unix- using awk to print in table format

I want to create a table that looks something like this, where i display the # at the front of every $2 and the Title header but I do not want to store it in my file:

Name          ID             Gender

John Smith    #4567734D      Male
Kyle Toh      #2437882L      Male
Julianne .T   #0324153T      Female

I got a result like this instead:

Name          ID             Gender
#
Name          ID             Gender
John Smith    #4567734D      Male
Name          ID             Gender
Kyle Toh      #2437882L      Male
Name          ID             Gender
Julianne .T   #0324153T      Female

By using this command:

awk -F: '   {print "Name:ID:Gender\n"} 
            {print $1":#"$2":"$3}' data.txt |column -s ":" -t

Upvotes: 0

Views: 2456

Answers (1)

hek2mgl
hek2mgl

Reputation: 157947

Print the headers only in the first line:

awk -F: 'NR==1 {print "Name:ID:Gender\n"} {print $1":#"$2":"$3}'

or:

awk -F: 'BEGIN {print "Name:ID:Gender\n"} {print $1":#"$2":"$3}'

Explanation:

An awk program consists of expressions in the form of:

CONDITION { ACTIONS } [ CONDITION { ACTIONS }, ... ]

... where CONDITION and ACTION optional. If CONDITION is missing, like:

{ ACTIONS }

... then ACTIONS would be applied to any line of input. In the case above we have two expressions:

# Only executed if NR==1
NR==1 {print "Name:ID:Gender\n"}

# CONDITION is missing. ACTIONS will be applied to any line of input
{print $1":#"$2":"$3}

Upvotes: 1

Related Questions