Bash Shell:从字符串/变量中删除(修剪)空白
时间:2020-01-09 10:37:24 来源:igfitidea点击:
我有一个bash变量,如下所示:
output="$(awk -F',' '/Name/ {print $9}' input.file)"
如何修剪bash变量$output中的前导和尾随空格?
如何修剪$output中的结尾空格?
您可以使用sed,awk,cut,tr和其他实用程序从$output中删除空格。
示例数据
定义一个称为ouput的变量:
output=" This is a test"
使用echo语句显示$output:
echo "=${output}="
示例输出:
= This is a test=
sed示例
语法为:
echo "${output}" | sed -e 's/^[ \t]*//'
输出示例:
This is a test
bash示例
删除前导空格语法是:
${var##*( )}
例如:
# Just remove leading whiltespace #turn it on shopt -s extglob output=" This is a test" output="${output##*( )}" echo "=${output}=" # turn it off shopt -u extglob
输出示例:
=This is a test=
要使用bash修剪开头和结尾的空格,请尝试:
#turn it on shopt -s extglob output=" This is a test " ### Trim leading whitespaces ### output="${output##*( )}" ### trim trailing whitespaces ## output="${output%%*( )} echo "=${output}=" # turn it off shopt -u extglob
输出示例:
=This is a test=
awk示例
语法为:
output=" This is a test " echo "=${output}=" ## Use awk to trim leading and trailing whitespace echo "${output}" | awk '{gsub(/^ +| +$/,"")} {print "="=This is a test="="}'
输出示例:
##代码##