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$//'