Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove white space from the end of line in linux [duplicate]

Tags:

linux

sed

i have file in which i want to remove white space from the end of line test.txt is as following (there is white space at the end of line.

ath-miRf10005-akr  ath-miRf10018-akr  ath-miRf10019-akr ath-miRf10020-akr  ath-miRf10023-akr ath-miRf10024-akr  

i used sed 's/$\s//' but it is not working.

like image 942
aksg24 Avatar asked Dec 11 '13 14:12

aksg24


People also ask

How do I remove whitespace at the end of a line in Linux?

Remove just spaces: $ sed 's/ *$//' file | cat -vet - hello$ bye$ ha^I$ # tab is still here! Remove spaces and tabs: $ sed 's/[[:blank:]]*$//' file | cat -vet - hello$ bye$ ha$ # tab was removed!

How do you get rid of trailing white space?

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 .

What removes white space from both ends of a string?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)

How do I trim extra spaces in Linux?

Use sed 's/^ *//g', to remove the leading white spaces. There is another way to remove whitespaces using `sed` command. The following commands removed the spaces from the variable, $Var by using `sed` command and [[:space:]]. $ echo "$Var are very popular now."


2 Answers

Use either a simple blank * or [:blank:]* to remove all possible spaces at the end of the line:

sed 's/ *$//' file 

Using the [:blank:] class you are removing spaces and tabs:

sed 's/[[:blank:]]*$//' file 

Note this is POSIX, hence compatible in both GNU sed and BSD.

For just GNU sed you can use the GNU extension \s* to match spaces and tabs, as described in BaBL86's answer. See POSIX specifications on Basic Regular Expressions.


Let's test it with a simple file consisting on just lines, two with just spaces and the last one also with tabs:

$ cat -vet file hello   $ bye   $ ha^I  $     # there is a tab here 

Remove just spaces:

$ sed 's/ *$//' file | cat -vet - hello$ bye$ ha^I$       # tab is still here! 

Remove spaces and tabs:

$ sed 's/[[:blank:]]*$//' file | cat -vet - hello$ bye$ ha$         # tab was removed! 
like image 64
fedorqui 'SO stop harming' Avatar answered Sep 26 '22 10:09

fedorqui 'SO stop harming'


Try this:

sed -i 's/\s*$//' youfile.txt 

On OS X:

sed -i '' 's/\s*$//' youfile.txt 
like image 41
BaBL86 Avatar answered Sep 24 '22 10:09

BaBL86