Praveen
Praveen

Reputation: 3

add row number to the last column using awk or bash

Input file format:

name id department
xyz  20  cic
abc  25  cis

Output should look like:

name id department
xyz  20  cic        1
abc  25  cis        2

Note: all the fields are tab separated.

Appreciate any help!!

Upvotes: 0

Views: 3050

Answers (3)

KGee
KGee

Reputation: 373

You should try this:

awk '{printf "%s\t%s\n",$0,NR}' File_name

Explanation:

$0 = print all the lines

NR = Adds number at each line

%s = for printing a literal character

\t = hozintal tab

\n = new line

Upvotes: 2

chepner
chepner

Reputation: 531430

A variation on Ed Morton's answer:

awk -F'\t' -v OFS='\t' 'NR>1 { $(NF+1)=NR-1} 1' file

This sets the output field separator using the -v option, then simply adds a new field to the current record by setting $(NR+1).

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203684

$ awk -F'\t' 'NR>1{$0=$0"\t"NR-1} 1' file
name    id      department
xyz     20      cic     1
abc     25      cis     2

Upvotes: 2

Related Questions