Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove trailing whitespaces for multiple files?

Are there any tools / UNIX single liners which would remove trailing whitespaces for multiple files in-place.

E.g. one that could be used in the conjunction with find.

like image 950
Mikko Ohtamaa Avatar asked May 22 '12 22:05

Mikko Ohtamaa


People also ask

How do I get rid of trailing whitespace?

Type M-x delete-trailing-whitespace to delete all trailing whitespace. This command deletes all extra spaces at the end of each line in the buffer, and all empty lines at the end of the buffer; to ignore the latter, change the variable delete-trailing-lines to nil .

How do you remove all trailing spaces in Notepad ++?

Alt + Shift + S is the default shortcut for this. It's in the menu bar as Macro -> Trim Trailing and save . You can rebind this under Settings -> Shortcut Mapper -> [Macros] .

Which function is used to remove whitespaces from the trailing end?

strip() Python String strip() function will remove leading and trailing whitespaces.

How do I remove a trailing space in Unix?

`sed` command is another option to remove leading and trailing space or character from the string data. The following commands will remove the spaces from the variable, $myVar using `sed` command. Use sed 's/^ *//g', to remove the leading white spaces.


2 Answers

You want

sed --in-place 's/[[:space:]]\+$//' file 

That will delete all POSIX standard defined whitespace characters, including vertical tab and form feed. Also, it will only do a replacement if the trailing whitespace actually exists, unlike the other answers that use the zero or more matcher (*).

--in-place is simply the long form of -i. I prefer to use the long form in scripts because it tends to be more illustrative of what the flag actually does.

It can be easily integrated with find like so:

find . -type f -name '*.txt' -exec sed --in-place 's/[[:space:]]\+$//' {} \+ 

If you're on a Mac

As pointed out in the comments, the above doesn't work if you don't have gnu tools installed. If that's the case, you can use the following:

find . -iname '*.txt' -type f -exec sed -i '' 's/[[:space:]]\{1,\}$//' {} \+ 
like image 62
Tim Pote Avatar answered Oct 14 '22 17:10

Tim Pote


Unlike other solutions which all require GNU sed, this one should work on any Unix system implementing POSIX standard commands.

find . -type f -name "*.txt" -exec sh -c 'for i;do sed 's/[[:space:]]*$//' "$i">/tmp/.$$ && mv /tmp/.$$ "$i";done' arg0 {} + 

Edit: this slightly modified version preserves the files permissions:

find . -type f -name "*.txt" -exec sh -c 'for i;do sed 's/[[:space:]]*$//' "$i">/tmp/.$$ && cat /tmp/.$$ > "$i";done' arg0 {} + 
like image 40
jlliagre Avatar answered Oct 14 '22 15:10

jlliagre