How to trim strings with bash

If you want to trim a string from or to a certain pattern, you don’t have to invoke cut, sed or awk. You can use the % operator to trim a string from the first or last occurrence of a pattern to the end or the # operator to trim from the beginning to the first or last occurrence of it.

The following bash script demonstrates how to use those operators.

#!/bin/bash

# the string to trim
TRIMME='hello world of tomorrow'

# the pattern to trim at
PATTERN=' '

echo "TRIMME = '$TRIMME'"
echo "PATTERN = '$PATTERN'"

# trim from the last occurrence of $PATTERN
echo "trim from the last occurrence of \$PATTERN"
echo "\${TRIMME%\$PATTERN*} = '${TRIMME%$PATTERN*}'"
# ${TRIMME%$PATTERN*} = 'hello world of'

# trim from the first occurrence of $PATTERN
echo "trim from the first occurrence of \$PATTERN"
echo "\${TRIMME%%\$PATTERN*} = '${TRIMME%%$PATTERN*}'"
# ${TRIMME%%$PATTERN*} = 'hello'

# trim to the first occurrence of $PATTERN
echo "trim to the first occurrence of \$PATTERN"
echo "\${TRIMME#*\$PATTERN} = '${TRIMME#*$PATTERN}'"
# ${TRIMME#*$PATTERN} = 'world of tomorrow'

# trim to the last occurrence of $PATTERN
echo "trim to the last occurrence of \$PATTERN"
echo "\${TRIMME##*\$PATTERN} = '${TRIMME##*$PATTERN}'"
# ${TRIMME##*$PATTERN} = 'tomorrow'

About h0nk3ym0nk3y

h0nk3ym0nk3y is one of the three LinuxM0nk3ys from Linux M0nk3ys @ WordPress Linux M0nk3ys @ YouTube Linux M0nk3ys @ Twitter

Posted on May 27, 2013, in Bash-Scripts, Command-Line and tagged , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: