我有一个文件test.txt,内容如下:
one
two
three
现在,我要按如下所示打印此文件的每一行:
.one (one)
.two (two)
.three (three)
我在Perl中尝试了此操作
@ARGV = ("test.txt");
while (<>) {
print (".$_ \($_\)");
}
这似乎不起作用,这就是我得到的:
.one
(one
).two
(two
).three
(three
)
有什么可以帮助我找出问题所在吗?
更新:
感谢Aureliano Guedes的建议。
这个1线似乎有效:
perl -pe's /([[^ \ s] +)/.$ 1($ 1)/'
答案 0 :(得分:5)
value_function
将包含换行符,例如val = int(line)
,因此$_
变成了one\n
之类的东西。
使用chomp
摆脱它们,或使用print ".$_ \($_\)"
删除所有结尾的空格。
print ".one\n (one\n)
(但是添加s/\s+\z//
来打印您要想要的换行符。)
答案 1 :(得分:2)
除了已经给出正确答案外,您还可以在oneliner中执行此操作:
perl -pe 's/(.+)/.$1 ($1)/'
或者,如果您希望使用while循环:
while (<>) {
s/(.+)/.$1 ($1)/;
print;
}
这只是将当前行修改为所需的输出,然后打印出来。
答案 2 :(得分:2)
另一种不使用正则表达式的Perl衬里。
perl -ple ' $_=".$_ ($_)" '
具有给定的输入
$ cat test.txt
one
two
three
$ perl -ple ' $_=".$_ ($_)" ' test.txt
.one (one)
.two (two)
.three (three)
$