Shell's method of removing Spaces or specifying characters from a string

  • 2021-01-03 21:15:48
  • OfStack

There are a lot of methods on the Internet, even though they are right, that don't work out right. Here's how to do it.

Remove the opening Spaces


$text=" 123 456 "
#  And this way of writing it, it's guaranteed to get the right answer. 
text=`echo $text | sed -e 's/^[ \t]*//g'`
#  There are no tests for these methods. Refer to the above methods. 
#  Remove the Spaces from the tail  sed 's/[ \t]*$//g'
#  Delete before and after the space, do not delete the middle space  sed -e 's/^[ \t]*//g' -e 's/[ \t]*$//g'
#  Delete all Spaces in the string  sed 's/[[:space:]]//g'

Of course there are easy ways:


#  Only replace 1 a 
text=${text/ /-}
#  All replacement 
text=${text// /-}

conclusion


Related articles: