Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a text file that has a space before the line. How do I delete it using tr (or the correct command)?

For example, I have this:


I would like this:


But, how do I do that for a 200 line text file?

I currently have this pipeline:

cat file.txt | tr -s " " | tr -d "," 

The other tr commands are for removing other aspects of the text files.

share|improve this question
If you have vim you can do the following: qa0xjq This ways you have recorded a macro under "a" key, that moves to the beginning of the line (0), deletes one character (x) and moves to the lines below (j). To repeat this macro 100 times simply type 100@a But beware, that this will remove all first characters from the document (assuming that every line has a preceding space, that's what you wanted to happen). – Melon Feb 5 '14 at 20:39
up vote 4 down vote accepted

This should do the job:

sed -e 's/^ //' -e 's/,//g' file.txt

The sed command (stream editor) is passed two commands to execute sequentially, both commands substitute something by nothing, i.e. delete a part of the input.

The first one removes spaces immediately following the beginning of a line, noted ^, the second one is removing the commas, and has the very same effect as your tr -d "," command.

Thanks to minerz029 for indirectly reminding me I was missing the 'g' as my first reply was only removing the first comma found in each line.

share|improve this answer
It will be great if you could explain all the parts of this command. – user68186 Feb 5 '14 at 20:25
It will remove one space following the start of the line. To remove more than one, use -e s/^ *// ;-) – Rmano Feb 5 '14 at 21:29
@Rmano Thats is correct however the OP asks to remove a single space. – jlliagre Feb 5 '14 at 21:34
Sorry for the slow response. We weren't given that command to use, but I will try it. If it works I'll use it. Thanks! – gbrooks Feb 10 '14 at 19:06
That worked perfectly, however is it possible to just use the command tr to do the same thing? – gbrooks Feb 10 '14 at 19:49
sed -e 's/^ //g' -e 's/,//g' file.txt


The first script (s/^ //g) is to replace all leading space with nothing (delete).
The second script (s/,//g) is to replace all commas with nothing (delete).

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.