In Bash how to strip trailing spaces and newlines?
Jul 5, 4:05pm

In Bash, you can strip trailing spaces and newlines from a string or a file using a combination of tools like sed, tr, or parameter expansion. Here are some common methods:


1. Strip Trailing Spaces and Newlines from a String

Using sed:

bash
echo "Hello World   " | sed 's/[[:space:]]*$//'
  • [[:space:]] matches any whitespace (spaces, tabs, etc.).
  • $ matches the end of the line.
  • This removes all trailing spaces and tabs.

To also remove trailing newlines:

bash
echo "Hello World   " | sed 's/[[:space:]]*$//;s/\n$//'

Using Parameter Expansion (for variables):

bash
var="Hello World   "
echo "${var% *}"  # Removes trailing spaces
echo "${var%$'\n'}"  # Removes trailing newline

2. Strip Trailing Spaces and Newlines from a File

Using sed (in-place editing):

bash
sed -i 's/[[:space:]]*$//' filename
  • -i edits the file in-place.

To also remove trailing newlines:

bash
sed -i 's/[[:space:]]*$//;s/\n$//' filename

Using tr (for newlines only):

bash
tr -d '\n' < filename  # Removes all newlines

3. Strip Trailing Spaces and Newlines from All Lines in a File

If you want to remove trailing spaces and newlines from every line in a file:

bash
sed -i 's/[[:space:]]*$//' filename
  • This removes trailing spaces from each line.

To also remove empty lines (if any):

bash
sed -i '/^[[:space:]]*$/d' filename

Jul 5, 4:05pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more