How to increment line counter for line beginning replacements by AWK/...?
nl
is a utility to number the lines of a file.Usage:
nl /path/to/file
In your specific case:
$ nl -s ' & ' input.txt
1 & What & South Dragon & North Dragon & 5 \\ \hline
2 & What & South Dragon & North Dragon & 5 \\ \hline
3 & What & South Dragon & North Dragon & 5 \\ \hline
This achieves what you're after. (as does awk '$0=NR" & "$0' filename
, but that's a bit cryptic)
awk '{print NR,"&",$0}' filename
1 & What & South Dragon & North Dragon & 5 \\ \hline
2 & What & South Dragon & North Dragon & 5 \\ \hline
3 & What & South Dragon & North Dragon & 5 \\ \hline
Or if sed
preferable, this gives same result.
sed = filename | sed 'N;s/\n/ \& /'
perl
approaches.
perl -pe '$_="$. & $_"' filename
perl -pe 's/^/$. & /' filename
Python can be a good alternative tool for this:
$ python -c "import sys;lines=[str(i)+' & '+l for i,l in enumerate(sys.stdin,1)]; print ''.join(lines)" < input.txt
1 & What & South Dragon & North Dragon & 5 \\ \hline
2 & What & South Dragon & North Dragon & 5 \\ \hline
3 & What & South Dragon & North Dragon & 5 \\ \hline
The way this works is that we redirect text into python's stdin, and read lines from there. enumerate()
function is what gives line count, with sys.stdin
specified as input and 1
is the starting index. The rest is simple - we make up list of new strings by casting index as string joined together with ' & '
string, and the line itself. Finally, all that is reassembled from list into one test by the ''.join()
function.
Alternatively , here's a multi-line version for a script file or simply for readability:
#!/usr/bin/env python
import sys
for index,line in enumerate(sys.stdin,1):
print str(index) + ' & ' + line.strip()
Works just the same:
$ ./line_counter.py < input.txt
1 & What & South Dragon & North Dragon & 5 \\ \hline
2 & What & South Dragon & North Dragon & 5 \\ \hline
3 & What & South Dragon & North Dragon & 5 \\ \hline
But if you prefer doing it in bash, then that can be done as well:
$ counter=1; while read line ; do printf "%s & %s\n" "$counter" "$line" ; counter=$(($counter+1)) ; done < input.txt
1 & What & South Dragon & North Dragon & 5 \ hline
2 & What & South Dragon & North Dragon & 5 \ hline
3 & What & South Dragon & North Dragon & 5 \ hline