Languages
[Edit]
EN

Bash - trim string

3 points
Created by:
Mark-Rotteveel
537

In this article, we would like to show you how to trim string using Bash.

Quick solution:

echo '   text   ' | awk 'match($0,/^\s*(.*)\s*$/,g){print g[1]}'

Note:

On the internet you can also find a solution using xargs, however it was not created to trim text and may damage your code.

 

Practical example

In this example, we create a reusable function that uses awk to trim the string that we pass as the first argument ($1).

#!/bin/bash

function trim_string() {
    echo "$1" | awk 'match($0,/^\s*(.*)\s*$/,g){print g[1]}'
}


# Usage example 1:

trim_string '   text   '

Alternative solution

In this example, we present a script that uses Bash wildcards to trim whitespace characters from the variable string.

script.sh file:

#!/bin/bash

variable="     text  "

# removes spaces from the beginning
variable="${variable#"${variable%%[![:space:]]*}"}"

# removes spaces from the end
variable="${variable%"${variable##*[![:space:]]}"}"   

echo "$variable"

Run in command line:

./script.sh

Output:

text

 

Alternative titles

  1. Bash - trim string variable
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join