Reputation: 23535
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
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 itjoin
adds the backslash and newline between each elementUpvotes: 3
Reputation: 126722
echo 'foo,bar' | perl -ne'print join " \\\n", map "BAZ($_)", /\w+/g'
output
BAZ(foo) \
BAZ(bar)
Upvotes: 3
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
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