How to ignore last newline in multiline line with Perl

I need to turn foo,bar

into

BAZ(foo) \
BAZ(bar)

      

\

there is as-is.

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

but created

BAZ(foo) \
BAZ(bar) \

      

So this is either a completely wrong approach, or I need a way to ignore the last newline in a multi-line string from Perl.

+3


source to share


4 answers


Using eof

to determine if you are on the last line:



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

      

0


source


You can use join

with map

for example:

$ echo 'foo,bar' | perl -F, -lape '$_ = join(" \\\n", map { "BAZ(" . $_ . ")" } @F)'
BAZ(foo) \
BAZ(bar)

      



  • -a

    enables automatic split mode by splitting the input with a separator ,

    and assigning it@F

  • map

    takes each element of the array and wraps it
  • join

    adds backslash and newline between each element
+3


source


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

      

Output

BAZ(foo) \
BAZ(bar)

      

+3


source


Using awk

, you can:

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)

      

+1


source







All Articles