Trim (Bash)

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen

How to trim a string in bash? See Parameter Substitution (Bash) for a lot of stuff that almost works.

xargs - Not OK

This works. Specifically: Bash parameter expansion didn't work when there are identical symbols to trim from both the beginning and end of the string. In that case, the whole string disappears.

However, it messes up various string (see the examples below) - I won't use this.

# OK - xargs - with spaces
########################################
#
i="   abc   "
echo ">>>${i}<<< - ${#i}"
i=$(echo $i | xargs)
echo ">>>${i}<<< - ${#i}"

 
# OK - xargs - with tabs
########################################
#
i="	abc					"
echo ">>>${i}<<< - ${#i}"
i=$(echo $i | xargs)
echo ">>>${i}<<< - ${#i}"


# OK - xargs - with tabs & spaces
########################################
#
i="  	abc 	 	 	"
echo ">>>${i}<<< - ${#i}"
i=$(echo $i | xargs)
echo ">>>${i}<<< - ${#i}"


# NOT OK - xargs - Double space inside
########################################
#
# This doesn't work, but that's not a problem for me
#
# i="a  b"
# echo ">>>${i}<<< - ${#i}"
# i=$(echo $i | xargs)
# echo ">>>${i}<<< - ${#i}"


# NOT OK - xargs - Odd number of single quotes
########################################
#
# This doesn't work, but is it a problem?
#
# i="a'b'c'"
# echo ">>>${i}<<< - ${#i}"
# i=$(echo $i | xargs)
# echo ">>>${i}<<< - ${#i}"


# NOT OK - xargs - It removes backslashes
########################################
#
# It's getting worse & worse
#
# i="a\b\c"
# echo ">>>${i}<<< - ${#i}"
# i=$(echo $i | xargs)
# echo ">>>${i}<<< - ${#i}"

grep - Quite OK

grep reduces multiple interior spaces to one space, but beyond that, it works much better than xargs. Fine for filtering URLs:

# OK - grep - Weird strings
########################################
#
# Quite good. I'm only not sure about double spaces
#
# i="  	h\o\'  hoi  hoi	 		 "
# echo ">>>${i}<<< - ${#i}"
# i=$(echo $i | grep .)
# echo ">>>${i}<<< - ${#i}"


# grep - Interior spaces get lost
########################################
#
# And that's fine for filtering URLs
#
i="h\/oi       h\\o\\i"
echo ">>>${i}<<< - ${#i}"
i=$(echo $i | grep .)
echo ">>>${i}<<< - ${#i}"

See also

Sources