4

How do I add a column to a text file, where the value is the row number?

File before:

Foo Ba Lk Q
Lorem ipsum doler

File after

1 Foo Ba Lk Q
2 Lorem ipsum doler

etc

2 Answers2

7

A few different approaches:

  1. cat

    $ cat -n file
        1   Foo Ba Lk Q
        2   Lorem ipsum doler
    
  2. Perl

    perl -pe 's/^/$. /' file
    

    The -pe means "print each input line after applying the script given by -e to it". Then, we replace ^ (the beginning of the line) with the line number ($.) and a space.

    Alternatively, since this is Perl and TIMTOWTDI:

    perl -ne 'print "$. $_"' file 
    perl -pe '$_ = "$. $_"' file 
    

    In all of these examples, if you want to modify the original file, use -i:

    perl -i -pe 's/^/$. /' file
    perl -i -ne 'print "$. $_"' file 
    perl -i -pe '$_ = "$. $_"' file 
    
  3. awk

    $ awk '{print NR,$0}' file
    1 Foo Ba Lk Q
    2 Lorem ipsum doler
    

    The special variable NR is the current line number and $0 the current line. To make the change in the original file (assuming you have a recent enough version of GNU awk), do:

    gawk -iinplace '{print NR,$0}' file
    
  4. sed

    $ sed = file | sed 'N;s/\n/\t/'
    1   Foo Ba Lk Q
    2   Lorem ipsum doler
    

    The = means "print the line number before every line". However, that prints the number on a line by itself and the input line under that. The second sed command puts them back on the same line again.

Jos
  • 29,224
terdon
  • 100,812
4

Just for fun

python3 -c "[print(i+1, l.strip())for i, l in enumerate(open('f').readlines())]"

Output:

1 Foo Ba Lk Q
2 Lorem ipsum doler

Where f is the path to your file, in quotes.

Explanation

open('f').readlines()

will read the file, in lines, and

enumerate(open('f').readlines())

will subsequently add a number to each of the lines, and

print(i+1, l.strip())

will print the number (+1, since the first index is 0) + the corresponding line

Jacob Vlijm
  • 83,767