I tried using

nl -ba -s '\t' full_media > full_media2

But it really did not add the tab, but it added actually the "\t" text after the line number. The file im editing is a CSV file and here by i'm trying to add a new column to the beginning with id.

  • 1
    Doesn't cat -n work? The command you propose but without -s '\t' seems to work too. What am I missing? – Celada Feb 9 '15 at 9:19
  • if i so not add -s part, it will just add the number to the 1st, but it will not add the tab separator with original column. Here I'm trying to add a new id column to my CSV file – dinesh707 Feb 9 '15 at 9:20
  • For me, both cat -n and nl -ba print the line number then a tab, then the original line contents. Maybe we are using different versions of the tools. – Celada Feb 9 '15 at 9:21
  • 1
    Real CSV files (not an artificial subset) can have newlines within a (quoted) cell value. Using your approach is going to mangle these CSV files. – Anthon Feb 9 '15 at 9:25

If you're using a modern shell like bash or zsh, use $ so that the shell evaluates \t and replaces it with an actual tab:

nl -ba -s $'\t' full_media > full_media2

Even so, if you examine the output, it looks like the default separator is a tab:

$ nl -ba -s $'\t' ~/at.sh | od -c
0000000                       1  \t   n   o   h   u   p       s   g    
$ nl -ba  ~/at.sh | od -c        
0000000                       1  \t   n   o   h   u   p       s   g    

Indeed, the default separator is tab, as specified by POSIX. From man nl:

   -s  sep
          Specify  the  characters  used in separating the line number and
          the corresponding text line. The default sep shall be a <tab>.

To add a column to the CSV, try using Python:

#! /usr/bin/env python2

from sys import stdin, stdout
import csv

csvin = csv.reader(stdin, delimiter='\t')
csvout= csv.writer(stdout, delimiter='\t')
count = 1

for row in csvin:
    csvout.writerow ([count] + row)
    count = count + 1

Save it as a script (say nl.py) and run:

python2 nl.py < full_media > full_media2
  • Is $'\t' available in standard Bourne shell? I think it might not be. – Celada Feb 9 '15 at 9:25
  • @Celada No, it isn't. I'll update. – muru Feb 9 '15 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.