Delete whitespace in each begin of line of file, using bash
Solution 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
Solution 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
Solution 3
use can use perl -i for in place replacement.
perl -p -e 's/^ *//' file
Solution 4
"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-
Solution 5
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
Comments
-
G-71 about 4 years
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
-
G-71 over 12 yearsand how i can change my file? The resut is wrote in console
-
G-71 over 12 yearsthis script delete all whitespaces
-
tripleee over 12 yearsYes, did your question somehow mean something else??
s/^ *//
deletes leading whitespace if that's what you want ... but perhaps you should also edit your question then. -
G-71 over 12 yearsThank you veru much and if i want to delete only whitespace in the begin of each line of file (excuse me i edit question :( )
-
Scharron over 12 yearsEdited to add @tripleee comment in the answer.
-
tripleee over 12 yearsThe
/g
is redundant but harmless in that case, the regex already takes care of substituting all leading whitespace in one go. -
Scharron over 12 yearsSure :-) Edited to have the simplest regexp.
-
Eric L. about 11 yearsYes, 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. -
CMCDragonkai about 10 yearsWhat about trailing whitespace?
-
Vince Varga over 7 yearsShouldn't it be
's/^\s*//'
so it removes tabs, too? -
Sigur almost 7 yearsHow to keep only the leading white spaces?
-
Saba over 3 yearsi was parsing XML file and only this helped.