Home » Questions » Computers [ Ask a new question ]

How can I prepend a line number and tab to each line of a text file?

How can I prepend a line number and tab to each line of a text file?

How can I append a line number and tab to the beginning of each line of a text file?

Asked by: Guest | Views: 399
Total answers/comments: 5
bert [Entry]

awk '{printf "%d\t%s\n", NR, $0}' < filename
bert [Entry]

"sed = test.txt | sed 'N;s/\n/\t/'

The command ""sed ="" will print the line number followed by a carriage return and then the next line.

The expression ""N;s/\n/\t/"" will take each line, get the next line (ie line number and the line), and replace the carriage return with a tab."
bert [Entry]

"How about

cat -n somefile.txt

?"
bert [Entry]

"OK, Here's a one-line bash solution:

$ IFS=$'\n';x=1;for l in $(<file.txt);do echo -e ""$x\t$l"";((x+=1));done
$ IFS=

The first IFS setting tells bash to read a full line at a time.
The second line resets the IFS to default.

As an added bonus, it runs completely in your shell and doesn't exec a program!"
bert [Entry]

"Ok, since we are collecting ways to do this,

grep -n . file.txt | sed 's/\(^[0-9]*\):/\1 /g'
# this is a tab with Ctrl-V + Tab =====> ----"