Delete whitespace in each begin of line of file, u

2020-02-23 07:26发布

问题:

How i can delete whitespace in each line of file, using bash For instance, file1.txt. Before:

  gg g
 gg g
t  ttt

after:

gg g
gg g
t  ttt

回答1:

sed -i 's/ //g' your_file will do it, modifying the file inplace.

To delete only the whitespaces at the beginning of one single line, use sed -i 's/^ *//' your_file

In the first expression, we replace all spaces with nothing. In the second one, we replace at the beginning using the ^ keyword



回答2:

tr(delete all whitespaces):

$ tr -d ' ' <input.txt >output.txt
$ mv output.txt input.txt

sed(delete leading whitespaces)

$ sed -i 's/^ *//' input.txt


回答3:

use can use perl -i for in place replacement.

perl -p -e 's/^ *//' file 


回答4:

To delete the white spaces before start of the line if the pattern matches. Use the following command. For example your foo.in has pattern like this

      This is a test                                
                    Lolll
                       blaahhh
      This is a testtt

After issuing following command

sed -e '/This/s/ *//' < foo.in > foo.out

The foo.out will be

This is a test
             Lolll
                blaahhh
This is a testtt