#! /bin/bash # helper script simulator VAR=" fu bar\n foo \n\n bar \n\n\n baz " echo -e "$VAR" | perl -nE ' # this code is used inside a loop because of -n option s/^\s+//; # remove leading whitespaces from lines s/\s+$/ /; # replace trailing whitespaces (including newlines) with a single whitespace $output .= $_; # append to a variable for later output # at the end, do this END { $output =~ s/\s+$//; # remove trailing whitespace say qq~>$output<~; # testing output #say $output; # production output } ' #END_OF_PERL