Unix-使用awk以表格格式打印

时间:2017-01-16 10:54:04

标签: unix awk

我想创建一个看起来像这样的表,我在每个$ 2的前面显示#和Title标题,但我不想将它存储在我的文件中:

Name          ID             Gender

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

我得到了这样的结果:

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

使用此命令:

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

1 个答案:

答案 0 :(得分:0)

仅在第一行打印标题:

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

或:

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

说明:

awk程序由以下形式的表达式组成:

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

...其中CONDITION和ACTION可选。如果缺少CONDITION,例如:

{ ACTIONS }

...然后ACTIONS将应用于任何输入行。在上面的例子中,我们有两个表达式:

# 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}