Reputation: 119
F1.txt
tom a b c d e boy
bob a b c sun
harry a c d e girl
result
F2.txt
tom1 a1 b1 c1 d1 e1 boy1
tom2 a2 b2 c2 sun2
tom3 a3 c3 d3 e3 girl3
Hello everyone, I am quite new to Perl,can you kindly help me out with this new problem of mine. I have a file F1.txt
, my job is to assign numbers after each string in a file according to its line number as shown in an example above. I have so far just managed to assign a number to each of the lines with this Perl one-liner
perl -pe '$_= ++$a." $_" if /./'
Upvotes: 2
Views: 166
Reputation: 57600
The special variable $.
holds the current line number.
The regex /(?<=\w)\b/g
matches each end of a word (or a number or underscore).
Or, more precise, a word boundary preceded by a "word" character which we don't include in our match. The \b
assertion has zero width. Use the regex s/(?<=\S)(?=\s|$)/$./g
to put a line number after each non-space sequence.
We can use the substitution operator s///g
to append the line number in this way:
echo -e "a b\nc d" | perl -ne 's/(?<=\w)\b/$./g; print'
prints
a1 b1
c2 d2
Upvotes: 2