내밥줄/프로그래밍

쉘 스크립트 각종 trim 방법

jjoell 2013. 1. 22. 16:57

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