tags:

views:

115

answers:

4

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?)

+5  A: 
sed "s/^[ \t]*//" -i youfile
shuvalov
thanks @shuvalov.
Lazer
+1  A: 

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.

Bryan Oakley
Indentation might be done with tabs...
João da Silva
@João da Silva: I modified my answer to reflect that. Thanks for the comment.
Bryan Oakley
@Bryan Oakley: thanks for explaining.
Lazer
A: 

Here you go:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt

Or:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt > file-out.txt
João da Silva
it will be shorter with -i(in-place) arg
shuvalov
thanks @João da Silva.
Lazer
+1  A: 

you can use awk

$ awk '{$1=$1}1' file
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++)

sed

$ sed 's|^[[:blank:]]*||g' file
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++)

shell's while/read loop

while read -r line
do
    echo $line
done <"file"
ghostdog74
thanks @ghostdog74!
Lazer