简体   繁体   English

打印文件的每一行

[英]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.

相关问题 在文件的每一行中分割一个字符串并打印字段 - split a string in each line in a file and print the fields 如何在每行之前用文件名打印文件内容? - How to print file contents with filename before each line? 逐行读取文件,并在没有匹配项时打印每行中的第一个匹配项或“ no_data” - Read file line by line and print the first match in each line or “no_data” when nothing matches 从perl中输出文件的每行中有五个单词的输入文件中打印para - To print a para from a input file having five words in each line in output file in perl 当我将文件读入数组并打印时,为什么在第一行之后的每一行的开头都有多余的空格? - When I read a file into an array and print it, why is there an extra whitespace at the beginning of each line after the first? Perl:如何解析文件并打印与用户输入的字符串匹配的每一行? - Perl: How to parse through a file and print each line that matches user inputted strings? 如何使用每个匹配的行打印行号? - How do I print the line number with each matched line? 文件每一行的Shell命令 - Shell command on each line of file 有没有办法打印两次但在每次打印调用之间休眠但都打印在同一行上? - Is there a way to print twice but sleep in between each print calls but have both print on the same line? 逐行读取文件并替换字符串,打印到文件 - Read a file line by line and replace a string, print to out file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM