How to trim leading and trailing white space in bash

In bash, you can trim leading and trailing white spaces from a string using parameter expansion.

  1. Trim leading white spaces: To trim leading white spaces from a string, you can use the following syntax:
string=" leading white spaces "
string="${string#"${string%%[![:space:]]*}"}"

This will remove any whitespace characters (spaces and tabs) at the beginning of the string.

  1. Trim trailing white spaces: To trim trailing white spaces from a string, you can use the following syntax:
string=" trailing white spaces "
string="${string%"${string##*[![:space:]]}"}"

This will remove any whitespace characters at the end of the string.

  1. Trim both leading and trailing white spaces: To trim both leading and trailing white spaces from a string, you can use the following syntax:
string=" leading and trailing white spaces "
string="${string#"${string%%[![:space:]]*}"}"
string="${string%"${string##*[![:space:]]}"}"

Please note that these commands are for a basic usage, and you can customize them according to your needs. Also, before making any changes, it’s recommended to have a backup plan in case something goes wrong, and also to test the changes before applying them to your production environment.

Additionally, you can use some command-line utilities like sed or awk to perform the trimming in a more efficient way.

Leave a Comment