In Bash how to remove the trailing space due to <kbd>tab</kbd>?
Jan 30, 3:02pm

In Bash, if you want to remove trailing spaces (including those caused by pressing the <kbd>Tab</kbd> key) from a string or a file, you can use parameter expansion or tools like sed or awk. Here are a few common methods:


1. Remove trailing spaces from a variable

Use Bash parameter expansion to trim trailing spaces from a variable:

bash
var="your string with trailing spaces " trimmed_var="${var%% *( )}" echo "$trimmed_var"

Or, for a more robust solution (handles multiple spaces):

bash
var="your string with trailing spaces " trimmed_var="${var%"${var##*[![:space:]]}"}" echo "$trimmed_var"

2. Remove trailing spaces from a file

Use sed to remove trailing spaces from each line in a file:

bash
sed -i 's/[[:space:]]*$//' filename
  • -i edits the file in-place.
  • [[:space:]]*$ matches any trailing spaces at the end of a line.

3. Remove trailing spaces from all files in a directory

To process all files in a directory:

bash
find . -type f -exec sed -i 's/[[:space:]]*$//' {} +

4. Using awk

You can also use awk to trim trailing spaces:

bash
awk '{sub(/[ \t]+$/, ""); print}' filename

To edit the file in-place, use a temporary file:

bash
awk '{sub(/[ \t]+$/, ""); print}' filename > tmp && mv tmp filename
Jan 30, 3:02pm

This Chat is read-only. Login to resume chatting.

var="your string with trailing spaces " trimmed_var="${var%% *( )}" echo "$trimmed_var"
var="your string with trailing spaces " trimmed_var="${var%"${var##*[![:space:]]}"}" echo "$trimmed_var"