user1758782
user1758782

Reputation: 43

Print each line of a file

I have a file test.txt that reads as follows:

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:

@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.
This 1-liner seems to work : perl -pe 's/([^\s]+)/.$1 ($1)/'

Upvotes: 2

Views: 393

Answers (3)

stack0114106
stack0114106

Reputation: 8711

Another Perl one-liner without using regex.

 perl -ple ' $_=".$_ ($_)" ' 

with the given inputs

$ cat test.txt
one
two
three

$ perl -ple ' $_=".$_ ($_)" ' test.txt
.one (one)
.two (two)
.three (three)

$

Upvotes: 2

Skeeve
Skeeve

Reputation: 8212

Besides the correct answer already given, you can do this in a oneliner:

perl -pe 's/(.+)/.$1 ($1)/'

Or if you prefer a while loop:

while (<>) {
    s/(.+)/.$1 ($1)/;
    print;
}

This simply modifies your current line to your desired output and prints it then.

Upvotes: 2

Biffen
Biffen

Reputation: 6355

$_ will include the newline, e.g. one\n, so print ".$_ \($_\)" becomes something like print ".one\n (one\n).

Use chomp to get rid of them, or use s/\s+\z// to remove all trailing whitespace.

while (<>) {
  chomp;
  print ".$_ ($_)\n";
}

(But add a \n to print the newline that you do want.)

Upvotes: 5

Related Questions