remove spaces

Hi folks,
I need to remove spaces at the end of each line in a *.txt file. it looks like this

word 1[space]
word 2[space]
.
.
.
word n[space]

i found some sed commands but any of them didnt work so far

thank you for your posts

for a text file named test.txt please try below:

cat test.txt|sed 's/ $//g'

1 Like

It doesn't hurt anything, but the global flag, g , in that substitution command is pointless. There can be only one match when the pattern is anchored.

Regards,
Alister

Thank you for your response, but it just didnt work for me again. the spaces are still at the end of each line.

Please, for future reference, "it just didnt work", is an unhelpful response. If you don't provide any feedback, it's unlikely that people will be able to help you out. What operating system and shell are you using? Exactly what command did you run? Did it generate an error message? Was there any output?

If I had to guess, you are expecting sed to modify the file when what sed does is read the file and write the changes its made to standard output, not to the original file itself. If that guess is correct, the following should work (back up your file first, just in case, or work with a copy of it):

printf '%s\n' '1,$s/ $//' w q | ed -s file

If that didn't work, are you sure that those are spaces and not some other blank character? You can verify using hd/hexdump/od. If you don't understand the output of those commands, simply paste them here. Don't forget to use code tags for code and data (to preserve formatting).

Regards,
Alister

1 Like

When I created a .txt file whit words and spaces and then used

cat /root/input.txt | sed 's/ *$//g' > output.txt 

it removed all spaces at the end of each line
but when I apply this to my file its not working. when I used the command

 cat /root/myfile.txt | sed 's/ *$/A/g' > myfile1.txt 

I got this:
word1[space]
A
word2[space]
A
...and so on
but it supposed to be:
word1A
word2A...
I suppose there's something wrong with this file. I merged 2 txt files and created one I want to remove spaces there now
there are no error messages, I always get an output file, but with no result
I didnt get it how can I verify whether there are some other blank characters
cant explain you better, sorry,I am a noob with poor eng.

---------- Post updated at 08:56 PM ---------- Previous update was at 08:25 PM ----------

I changed encoding of the whole document to ISO 8859-15 and performed

 cat input.txt | sed 's/ *$//g' > output.txt 

and it finally worked
Thank You again for your responses

Thank you for reporting back with your solution. Welcome to the forums.

Regards,
Alister