0

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
1
  • 1
    Please edit your question to show us the sample input as well. Commented Jan 16, 2017 at 11:01

1 Answer 1

1

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}
Sign up to request clarification or add additional context in comments.

4 Comments

Or perhaps more typically, in a begin block: BEGIN{print "Name:ID:Gender\n"}
Sure, BEGIN can be used as well.
@hek2mgl Now although the title does not duplicate anymore, how do I avoid printing the # on the second line and keep it blank?
Just print $1:"":$3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.