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:
sed:bashecho "Hello World " | sed 's/[[:space:]]*$//'
[[:space:]] matches any whitespace (spaces, tabs, etc.).$ matches the end of the line.To also remove trailing newlines:
bashecho "Hello World " | sed 's/[[:space:]]*$//;s/\n$//'
bashvar="Hello World " echo "${var% *}" # Removes trailing spaces echo "${var%$'\n'}" # Removes trailing newline
sed (in-place editing):bashsed -i 's/[[:space:]]*$//' filename
-i edits the file in-place.To also remove trailing newlines:
bashsed -i 's/[[:space:]]*$//;s/\n$//' filename
tr (for newlines only):bashtr -d '\n' < filename # Removes all newlines
If you want to remove trailing spaces and newlines from every line in a file:
bashsed -i 's/[[:space:]]*$//' filename
To also remove empty lines (if any):
bashsed -i '/^[[:space:]]*$/d' filename
Vibe can make mistakes. Check answers. Learn more