简体   繁体   中英

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' echo 'foo,bar' | tr , '\\n' | perl -pe 's/(.*)\\n/BAZ($1) \\\\\\n/g' 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.

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

output

BAZ(foo) \
BAZ(bar)

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)

使用eof检测您是否在最后一行:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM