Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove leading whitespace from each line in a file

Tags:

grep

unix

sed

awk

I have a file that looks something like this:

for (i = 0; i < 100; i++)     for (i = 0; i < 100; i++)   for (i = 0; i < 100; i++)        for (i = 0; i < 100; i++)      for (i = 0; i < 100; i++)            for (i = 0; i < 100; i++) for (i = 0; i < 100; i++) 

I want it to look like this (remove indentations):

for (i = 0; i < 100; i++) for (i = 0; i < 100; i++) for (i = 0; i < 100; i++) for (i = 0; i < 100; i++) for (i = 0; i < 100; i++) for (i = 0; i < 100; i++) for (i = 0; i < 100; i++) 

How can this be done (using sed maybe?)?

like image 608
Lazer Avatar asked Feb 22 '10 11:02

Lazer


People also ask

How do you remove leading spaces using sed?

Use sed 's/^ *//g', to remove the leading white spaces.

How do I remove an extra space at the end of a line in Unix?

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 I get rid of extra spaces in Linux?

s/[[:space:]]//g; – as before, the s command removes all whitespace from the text in the current pattern space.

Which of the following removes all leading whitespace?

Answer. lstrip() removes leading white-spaces, rstrip() removes trailing white-spaces and strip() removes leading and trailing white-spaces from a given string.


2 Answers

sed "s/^[ \t]*//" -i youfile 

Warning: this will overwrite the original file.

like image 149
shuvalov Avatar answered Sep 22 '22 10:09

shuvalov


For this specific problem, something like this would work:

$ sed 's/^ *//g' < input.txt > output.txt 

It says to replace all spaces at the start of a line with nothing. If you also want to remove tabs, change it to this:

$ sed 's/^[ \t]+//g' < input.txt > output.txt 

The leading "s" before the / means "substitute". The /'s are the delimiters for the patterns. The data between the first two /'s are the pattern to match, and the data between the second and third / is the data to replace it with. In this case you're replacing it with nothing. The "g" after the final slash means to do it "globally", ie: over the entire file rather than on only the first match it finds.

Finally, instead of < input.txt > output.txt you can use the -i option which means to edit the file "in place". Meaning, you don't need to create a second file to contain your result. If you use this option you will lose your original file.

like image 23
Bryan Oakley Avatar answered Sep 23 '22 10:09

Bryan Oakley