2

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.

4
  • 1
    Doesn't cat -n work? The command you propose but without -s '\t' seems to work too. What am I missing? Commented Feb 9, 2015 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 Commented Feb 9, 2015 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. Commented Feb 9, 2015 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. Commented Feb 9, 2015 at 9:25

1 Answer 1

4

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
2
  • Is $'\t' available in standard Bourne shell? I think it might not be. Commented Feb 9, 2015 at 9:25
  • @Celada No, it isn't. I'll update. Commented Feb 9, 2015 at 9:26

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.