How do I trim lines read from standard input on bash?
You can use sed to trim it.
sed 's/^ *//;s/ *$//'
You can test it really easily on a command line by doing:
echo -n " 12 s3c " | sed 's/^ *//;s/ *$//' && echo c
$ trim () { read -r line; echo "$line"; }
$ echo " aa bb cc " | trim
aa bb cc
$ a=$(echo " aa bb cc " | trim)
$ echo "..$a.."
..aa bb cc..
To make it work for multi-line input, just add a while
loop:
trim () { while read -r line; do echo "$line"; done; }
Using sed
with only one substitution:
sed 's/^\s*\(.*[^ \t]\)\(\s\+\)*$/\1/'