F1.txt
tom a b c d e boy
bob a b c sun
harry a c d e girl
的结果 的
F2.txt
tom1 a1 b1 c1 d1 e1 boy1
tom2 a2 b2 c2 sun2
tom3 a3 c3 d3 e3 girl3
大家好,我是Perl的新手,能否帮助我解决我的这个新问题。我有一个文件F1.txt
,我的工作是根据文件中的行号在文件中的每个字符串后面分配数字,如上例所示。到目前为止,我已经设法使用这个Perl单行
perl -pe '$_= ++$a." $_" if /./'
答案 0 :(得分:2)
可能如下:
perl -pe 's/(?<=\w)\b/$./g;'
答案 1 :(得分:2)
特殊变量$.
包含当前行号。
正则表达式/(?<=\w)\b/g
匹配单词(或数字或下划线)的每一端。
或者,更准确地说,一个单词边界前面有一个“单词”字符,我们在匹配中不包括这个字符。 \b
断言的宽度为零。使用正则表达式s/(?<=\S)(?=\s|$)/$./g
在每个非空格序列后面添加行号。
我们可以使用替换运算符s///g
以这种方式追加行号:
echo -e "a b\nc d" | perl -ne 's/(?<=\w)\b/$./g; print'
打印
a1 b1
c2 d2
答案 2 :(得分:0)
在单行中:
perl -pe 's/(?<=\w)\b/$./g' F1.txt >F2.txt