Updated April 15, 2023
Introduction to Bash Trim String
In the article for bash trim string, at first, we would like to know about the meaning and intention behind the trim feature in bash. In a literal sense, we mean trim as removal of any unwanted or irregular parts. Similarly, in the world of bash, these unwanted or irregular parts can be anything starting from whitespaces or any other character which deems fit. In general, sense whenever we talk about the trim, we specifically refer to the removal of whitespaces in bash. These whitespaces are not the ones that appear between the words in a sentence but more from a perspective that whitespaces are present at the start and end of the sentence. In this article we will look at all the methodologies we take in order to utilize this feature and concept!
Syntax:
There are 4 ways in which we cater to exploit the feature of trim of whitespaces.
- Parameter Expansion: In cases of removal of any character from the beginning or end of the string, one can use the utility of parameter expansion to attain the required result. An example in our article will help you understand it much better and that is what our next section is meant for!
- Sed Command: We have been emphasizing the fact that sed and awk commands is capable of performing complex data science transformations and trimming strings seems a basic transformation for sed command. For leading whitespace we use sed ‘s/^ *//g’, for trailing we would use sed ‘s/ *$//g’ and nowadays another popular methodology is to use sed -e ‘s/^[[:space:]]*//’.
- Awk Command: In competition to sed commands, awk doesn’t stay behind. For removal of spaces from beginning we would use awk ‘{gsub(/^[ ]+/,””), for end of the string we would use awk ‘{gsub(/[ ]+$/,””) and incase both the operations are needed we would use awk ‘{gsub(/^[ ]+| [ ]+$/,””)
- Xargs Command: Did we say that there is no in-built function for trimming? But this keyword acts as a function to perform the trim operation. Be careful that in programing language we can’t call xargs as function, it is just a command!
How does String Trim Function Work in Bash?
In understanding how to string trim function work we need to look at what strings are, and which category does trim function fall into. The string is nothing but a combination of characters having a place in the placeholder of variables. The trim function falls into a concept of string manipulation which has similar other features. The reason removal of whitespaces is so popular is because of the huge data which might be fed in from a raw file tends to produce a lot of unnecessary whitespaces and they are unwanted from the scenario perspective.
Let us get now straight to the topic of interest and that is trim of string. The process of trimming is to remove any leading or trailing whitespaces from a string. In case you have been a regular user of some other standard programming language, you would be well acquainted with the functionality of a trim function, though it is unfortunate that such function is non-existent in bash. Nevertheless, there are a few options available for the removal of unwanted characters and so they are well extended to the utility of trimming strings! Some of these methods which we mentioned in the section of syntax and would explain in detail includes, parameter expansion, sed, awk, xargs, and many such more! So, let us get to the point of understanding each one of them in detail. We should be cognizant of the fact of leading and trailing whitespace. Leading whitespaces occurs before the start of the sentence and trailing whitespace occurs at the end of the sentence.
- Parameter Expansion: In the parameter expansion, we look into some characteristics of the command like we use %for removing the leading whitespace and use # for removing of the trailing whitespace.
- Sed Command: Sed command is a bit different from parameter expansion in terms of keyword used for removing trailing and leading whitespace. We use ^for removing the leading whitespace and use $ for removing of the trailing whitespace.
- Awk Command: The only difference lies in the command awk being used in place of sed. Rest we use ^ for removing the leading whitespace and use $ for removing the trailing whitespace. It again depends on the comfortableness of a user to pick either of sed and awk to fulfill the requirement.
- Xargs Command: In case one needs to remove both trailing and leading whitespace xargs can be used. Though sed and awk gives the option of removing trailing and leading specifically, xargs helps in removing both in one go and short syntax!
Example of Bash Trim String
Once here, we will look at a real-life problem statement, and we would solve this by showing it as a part of an example. For the sake of simplicity, we have kept features in the code minimalistic, but keeping the thinking behind for solving will be real-life one!
Code:
#!/bin/bash
echo "Exmaple to show how to remove trailing or leading whitespaces"
var=" Text with whitespace "
echo "Method 1: Parameter Expansion"
var_1=$var
echo "Print with both lead and trail whitespace $var_1 <fullstop>"
var_1_1="${var_1#"${var_1%%[![:space:]]*}"}"
var_1_2="${var_1%"${var_1##*[![:space:]]}"}"
echo "Remove leading whitespace $var_1_1 <fullstop>"
echo "Remove trailing whitespace $var_1_2 <fullstop>"
echo "Method 2: sed command"
echo "Print with both lead and trail whitespace $var <fullstop>"
myVar_lead=$var
myVar_trail=$var
myVar_lead=$(echo "$myVar_lead" | sed 's/^[ ]*//')
echo "Remove leading whitespace $myVar_lead<fullstop>"
myVar_trail=$(echo "$myVar_trail" | sed 's/[ ]*$//')
echo "Remove trailing whitespace $myVar_trail<fullstop>"
echo "Method 3: awk command"
echo "Print with both lead and trail whitespace $var <fullstop>"
echo "Remove leading whitespace $(echo "${var}" | awk '{gsub(/^[ ]+/,""); print $0, "<fullstop>" }')"
echo "Remove trailing whitespace $(echo "${var}" | awk '{gsub(/[ ]+$/,""); print $0, "<fullstop>" }')"
echo "Removing both whitespaces $(echo "${var}" | awk '{gsub(/^[ ]+| [ ]+$/,""); print $0, "<fullstop>" }')"
echo "Method 4: xargs command"
echo "Print with both lead and trail whitespace $var <fullstop>"
echo "Removing both whitespaces $(echo "$var" | xargs) <fullstop>"
Output:
Conclusion
With the examples, it is now evident of the usage of utility in bash for trimming string. Instead of trim, one can also use this utility to remove some characters as well. We hope you had fun while going through an article and we bid adieu till we meet for yet another article on bash!
Recommended Articles
We hope that this EDUCBA information on “Bash Trim String” was beneficial to you. You can view EDUCBA’s recommended articles for more information.