Go Back   The UNIX and Linux Forums > Top Forums > UNIX for Dummies Questions & Answers


UNIX for Dummies Questions & Answers If you're not sure where to post a UNIX or Linux question, post it here. All UNIX and Linux newbies welcome !!

Reply    
 
Thread Tools Search this Thread Display Modes
    #1  
Old 12-19-2012
Registered User
 
Join Date: May 2011
Posts: 190
Thanks: 92
Thanked 0 Times in 0 Posts
Adding a column to a text file with row numbers

Hi,

I would like to add a new column containing the row numbers to a text file. How do I go about doing that? Thanks!

Example input:

Code:
A X
B Y
C D

Output:

Code:
A X 1
B Y 2
C D 3

Sponsored Links
    #2  
Old 12-19-2012
Scrutinizer's Avatar
Moderator
 
Join Date: Nov 2008
Location: Amsterdam
Posts: 7,394
Thanks: 144
Thanked 1,757 Times in 1,594 Posts
What have you tried?
Sponsored Links
    #3  
Old 12-20-2012
bmk bmk is offline
Registered User
 
Join Date: Dec 2011
Posts: 258
Thanks: 1
Thanked 22 Times in 22 Posts
Try like...


Code:
 sed "=" test1.txt | sed "N;s/\n/ /"

    #4  
Old 12-20-2012
Scrutinizer's Avatar
Moderator
 
Join Date: Nov 2008
Location: Amsterdam
Posts: 7,394
Thanks: 144
Thanked 1,757 Times in 1,594 Posts
On your path this would put the line numbers at the end:

Code:
sed = test1.txt | sed 'N;s/\(.*\)\n\(.*\)/\2 \1/'

An awk alternative would be:

Code:
awk '{print $0,NR}' test1.txt

Sponsored Links
    #5  
Old 12-20-2012
sathyaonnuix's Avatar
Registered User
 
Join Date: Aug 2012
Posts: 121
Thanks: 34
Thanked 13 Times in 12 Posts
Use this if the position of the new column never matters,

try nl command


Code:
nl filename


Code:
# cat file
asddg
asgfdfgh
sdastg
djsf
fj


Code:
# nl file
     1  asddg
     2  asgfdfgh
     3  sdastg
     4  djsf
     5  fj

Sponsored Links
    #6  
Old 12-20-2012
rangarasan's Avatar
Registered User
 
Join Date: Jul 2011
Location: Chennai, India
Posts: 484
Thanks: 9
Thanked 119 Times in 115 Posts
perl

Hi,

Try this one,


Code:
perl -nle 'print "$_ $.";' input_file

Cheers,
Ranga
Sponsored Links
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
Adding row of numbers SkySmart Shell Programming and Scripting 12 06-13-2012 03:14 AM
How do you delete cells from a space delimited text file given row and column number? evelibertine UNIX for Dummies Questions & Answers 5 06-01-2011 01:41 PM
Adding a column to a text based on file name rlapate Shell Programming and Scripting 12 05-23-2009 09:22 PM
Adding a new column in a text file snahata Shell Programming and Scripting 10 03-13-2009 07:00 AM
Changing the column for a row in a text file and adding another row aYankeeFan Shell Programming and Scripting 9 05-02-2005 09:42 PM



All times are GMT -4. The time now is 09:09 PM.