[英]Print each line of a file
I have a file test.txt that reads as follows: 我有一个文件test.txt,内容如下:
one
two
three
Now, I want to print each line of this file as follows: 现在,我想打印此文件的每一行,如下所示:
.one (one)
.two (two)
.three (three)
I try this in Perl: 我在Perl中尝试这个:
@ARGV = ("test.txt");
while (<>) {
print (".$_ \($_\)");
}
This doesn't seem to work and this is what I get: 这似乎不起作用,这是我得到的:
.one
(one
).two
(two
).three
(three
)
Can some help me figure out what's going wrong? 有人可以帮我弄清楚出了什么问题吗?
Update : Thanks to Aureliano Guedes for the suggestion. 更新:感谢Aureliano Guedes提出的建议。
This 1-liner seems to work : perl -pe 's/([^\\s]+)/.$1 ($1)/' 这个1-liner似乎有效:perl -pe's /([^ \\ s] +)/. $ 1($ 1)/'
$_
will include the newline, eg one\\n
, so print ".$_ \\($_\\)"
becomes something like print ".one\\n (one\\n)
. $_
将包含换行符,例如one\\n
,因此print ".$_ \\($_\\)"
变成类似print ".one\\n (one\\n)
。
Use chomp
to get rid of them, or use s/\\s+\\z//
to remove all trailing whitespace. 使用chomp
去除它们,或使用s/\\s+\\z//
删除所有尾随空格。
while (<>) {
chomp;
print ".$_ ($_)\n";
}
(But add a \\n
to print the newline that you do want.) (但是添加\\n
来打印你想换行。)
Besides the correct answer already given, you can do this in a oneliner: 除了已经给出的正确答案,你可以在一个oneliner上做到这一点:
perl -pe 's/(.+)/.$1 ($1)/'
Or if you prefer a while loop: 或者如果你喜欢while循环:
while (<>) {
s/(.+)/.$1 ($1)/;
print;
}
This simply modifies your current line to your desired output and prints it then. 这只是简单地将当前行修改为您想要的输出并打印出来。
Another Perl one-liner without using regex. 另一个不使用正则表达式的Perl单线程。
perl -ple ' $_=".$_ ($_)" '
with the given inputs 给定的输入
$ cat test.txt
one
two
three
$ perl -ple ' $_=".$_ ($_)" ' test.txt
.one (one)
.two (two)
.three (three)
$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.