trim() {
local var=$1 var="${var#"${var%%[![:space:]]*}"}" # remove leading whitespace characters var="${var%"${var##*[![:space:]]}"}" # remove trailing whitespace characters echo -n "$var" }
var=`hg st -R "$path" | tr -d '\n'`
if [ -n $var ]; then
echo $var
done
$ var='abc def'
$ echo "$var"
abc def
# Note: flussence's original expression was "${var/ /}", which only replaced the *first* space char., wherever it appeared.
$ echo -n "${var//[[:space:]]/}"
abcdef
var=`hg st -R "$path" | sed -e 's/ *$//'`
trim() {
# Determine if 'extglob' is currently on.
local extglobWasOff=1
shopt extglob >/dev/null && extglobWasOff=0
(( extglobWasOff )) && shopt -s extglob # Turn 'extglob' on, if currently turned off.
# Trim leading and trailing whitespace
local var=$1
var=${var##+([[:space:]])}
var=${var%%+([[:space:]])}
(( extglobWasOff )) && shopt -u extglob # If 'extglob' was off before, turn it back off.
echo -n "$var" # Output trimmed string.
}
trim()
{
trimmed=$1
trimmed=${trimmed%% }
trimmed=${trimmed## }
echo $trimmed
}
$ var=`echo ' hello'`; echo $var
hello
# Trim whitespace from both ends of specified parameter
trim () {
read -rd '' $1 <<<"${!1}"
}
# Unit test for trim()
test_trim () {
local foo="$1"
trim foo
test "$foo" = "$2"
}
test_trim hey hey &&
test_trim ' hey' hey &&
test_trim 'ho ' ho &&
test_trim 'hey ho' 'hey ho' &&
test_trim ' hey ho ' 'hey ho' &&
test_trim $'\n\n\t hey\n\t ho \t\n' $'hey\n\t ho' &&
test_trim $'\n' '' &&
test_trim '\n' '\n' &&
echo passed
$ xyz=`echo -e 'foo \n bar'`
$ echo $xyz
foo bar
echo " This is a test" | sed "s/^[ \t]*//"
echo " lol " | xargs
echo $var | awk '{gsub(/^ +| +$/,"")}1'
MYVAR=`git ls-files -m|wc -l|tr -d ' '`
function trim {
local trimmed="$@"
if [[ "$trimmed" =~ " *([^ ].*[^ ]) *" ]]
then
trimmed=${BASH_REMATCH[1]}
fi
echo "$trimmed"
}
echo "'$(trim " one two three ")'"
read -r var << eof
$var
eof
var="$(hg st -R "$path" | sed "s/\(^ *\| *\$\)//g")"
if [ -n "$var" ]; then
echo "[${var}]"
fi
'내밥줄 > 프로그래밍' 카테고리의 다른 글
[bash] unset 변수와 empty 값 변수 구별 (0) | 2013.01.25 |
---|---|
[펌]All about Variables in Bash | Shell Scripting (0) | 2013.01.23 |
[펌]메모리 누수 Valgrind로 막아 보자 (0) | 2012.10.24 |
[펌]Linux /dev/random vs /dev/urandom 삽질 후기 (0) | 2011.08.16 |
[펌]vim 플러그인 모음과 .vimrc 파일 (0) | 2009.11.23 |