Marcel Stör
Marcel Stör

Reputation: 23535

How to ignore last newline in a multiline string with Perl

I need to turn foo,bar into

BAZ(foo) \
BAZ(bar)

The \ is there as-is.

I tried with echo 'foo,bar' | tr , '\n' | perl -pe 's/(.*)\n/BAZ($1) \\\n/g' but that produces

BAZ(foo) \
BAZ(bar) \

So, this is either a totally wrong approach or I'd need a way to ignore the last newline in a multiline string with Perl.

Upvotes: 3

Views: 234

Answers (4)

Tom Fenech
Tom Fenech

Reputation: 74615

You could use join with map, like this:

$ echo 'foo,bar' | perl -F, -lape '$_ = join(" \\\n", map { "BAZ(" . $_ . ")" } @F)'
BAZ(foo) \
BAZ(bar)
  • -a enables auto-split mode, splitting the input using the , delimiter and assigning it to @F
  • map takes every element of the array and wraps it
  • join adds the backslash and newline between each element

Upvotes: 3

Borodin
Borodin

Reputation: 126722

echo 'foo,bar' | perl -ne'print join " \\\n", map "BAZ($_)", /\w+/g'

output

BAZ(foo) \
BAZ(bar)

Upvotes: 3

RobEarl
RobEarl

Reputation: 7912

Using eof to detect if you're on the last line:

echo 'foo,bar' | tr , '\n' | perl -pe 'my $break = (eof) ? "" : "\\"; s/(.*)\n/BAZ($1) $break\n/g'

Upvotes: 0

anubhava
anubhava

Reputation: 785156

Using awk you can do:

s='foo,bar'
awk -F, '{for (i=1; i<=NF; i++) printf "BAZ(%s) %s\n", $i, (i<NF)? "\\" : ""}' <<< "$s"
BAZ(foo) \
BAZ(bar)

Or using sed:

sed -r 's/([^,]+)$/BAZ(\1)/; s/([^,]+),/BAZ(\1) \\\n/g' <<< "$s"
BAZ(foo) \
BAZ(bar)

Upvotes: 1

Related Questions