16

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
F1Linux
  • 3,580
  • 3
  • 25
  • 24
G-71
  • 3,626
  • 12
  • 45
  • 69

5 Answers5

30

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

Sirex
  • 219
  • 4
  • 22
Scharron
  • 17,233
  • 6
  • 44
  • 63
16

tr(delete all whitespaces):

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

sed(delete leading whitespaces)

$ sed -i 's/^ *//' input.txt
kev
  • 155,172
  • 47
  • 273
  • 272
4

use can use perl -i for in place replacement.

perl -p -e 's/^ *//' file 
Vijay
  • 65,327
  • 90
  • 227
  • 319
  • Yes, yes! I was looking for a clean, quick way of stripping all beginning and trailing whitespace from lines in source code files. The above code strips the newline characters, not a desirable trait for my purposes, so `perl -pi -e 's/^[\ \t]+|[\ \t]+$//g' [file]` does exactly what I needed. – Eric L. Jun 13 '13 at 17:21
1

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
Sopan Kurkute
  • 128
  • 1
  • 9
1

"Whitespace" can include both spaces AND tabs. The solutions presented to date will only match and operate successfully on spaces; they will fail if the whitespace takes the form of a tab.

The below has been tested on the OP's specimen data set with both spaces AND tabs, matching successfully & operating on both:

sed 's/^[[:blank:]]*//g' yourFile

After testing, supply the -i switch to sed to make the changes persistent-

F1Linux
  • 3,580
  • 3
  • 25
  • 24