How-To
You can use a bash parameter expansion, sed, cut and tr to trim a string.
Bash parameter expansion
Let's use bash parameter expansion to remove all whitespace characters from the variable foo:
- test1.sh
- #!/bin/sh
- foo="Hello world."
- echo "${foo//[[:space:]]/}"
Using sed command to trim the front/back space
To remove only space characters before and after string use sed:
- test2.sh
- #!/bin/sh
- foo=" Hello world. "
- echo "${foo}" | sed -e 's/^[[:space:]]*//'
Using xargs to remove space
Easy to use and remember way how to remove whitespaces before and after word:
- test3.sh
- #!/bin/sh
- foo=" Hello world. "
- foo_remove_space=`echo ${foo} | xargs`
- echo "foo_remove_space='${foo_remove_space}'"
Supplement
* Split string by delimiter and get N-th element
* Linux 系統 xargs 指令範例與教學
沒有留言:
張貼留言