Reputation: 19109
I have file with few lines, I want combine all lines with delimiter and remove the last one.
Its not working with perl. but working with sed. can you help to make this work with perl?
cat a
a
b
c
d
cat a |perl -lane 'printf("%s|",$_)' |perl -lane 's/|$//;print'
a|b|c|d|
cat a |perl -lane 'printf("%s|",$_)' |sed 's/|$//'
a|b|c|d
Upvotes: 1
Views: 472
Reputation: 385849
Why add then remove?
perl -pe'chomp; $_="|$_" if $. > 1; END { print "\n"; }'
By the way,
cat file | perl -e'...' # Useless use of cat
can be written as
perl -e'...' <file
And since all solutions provided read from ARGV, you can even drop the redirection and pass the file name as an argument.
perl -e'...' file
For fun, golfing:
perl -pE'chomp;$.>1&&s/^/|/;END{say""}' # Based on mine
perl -nlE'push@L,$_}{$"="|";say"@L"' # Based on JRF's
perl -E'chomp(@L=<>);say join"|",@L'
perl -0777pe's/\n(?!\z)/|/g'
Only the first wastes no memory. The last one is probably the fastest.
Upvotes: 5
Reputation: 7516
join makes this trivial. You could do:
cat a | perl -lne'push @lines,$_;END{print join "|", @lines}'
...but then you get the useless cat
award, so reduce that to:
perl -lne'push @lines,$_;END{print join "|", @lines}' a
a|b|c|d
Upvotes: 4
Reputation: 33370
Try escaping it,
cat a |perl -lane 'printf("%s|",$_)' |perl -lane 's/\|$//;print'
Perl sees |
as an or
in a search-and-replace.
Upvotes: 2