Delete Whitespace in Each Begin of Line of File, Using Bash

Delete whitespace in each begin of line of file, using bash

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

Removing all spaces from the beginning of lines

You can use this sed command to remove leading whitespace (spaces or tabs)

sed 's/^[ \t]*//' file 

Use sed -i to modify the file in-place.

Bash - How to remove all white spaces from a given text file?


$ man tr
NAME
tr - translate or delete characters

SYNOPSIS
tr [OPTION]... SET1 [SET2]

DESCRIPTION
Translate, squeeze, and/or delete characters from standard
input, writing to standard output.

In order to wipe all whitespace including newlines you can try:

cat file.txt | tr -d " \t\n\r" 

You can also use the character classes defined by tr (credits to htompkins comment):

cat file.txt | tr -d "[:space:]"

For example, in order to wipe just horizontal white space:

cat file.txt | tr -d "[:blank:]"

How to remove leading whitespace from each line in a file


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

Warning: this will overwrite the original file.

bash how to replace/delete beginning of line followed by white space

I'd use sed.

sed -E '/^\s*$/d; s/^\s*//;' < in > out

This deletes lines with only whitespace, and strips whitespace off the beginning of other lines.

c.f. https://www.gnu.org/software/sed/manual/sed.html

There are refinements, but this is the general idea.

sed not removing all whitespaces from the beginning of each line in the file

The problem here is because your file contains some \t in the beginning of the lines as shown by cat -vTE (as requested in my comment)

bash-3.2$ cat -vte remove_space.txt
this is firs line with 2-3 spaces$
^I^I^I^I2nd line with more space, this is where the issue is.$
3rd line $

You can change your command into:

sed -E 's/^[[:space:]]+//' remove_space.txt 

to take care of the spaces and the tabs. Also for portability reasons use POSIX regex as defined in the help https://www.freebsd.org/cgi/man.cgi?query=sed&sektion=&n=1

 -E        Interpret regular expressions as extended (modern) regular
expressions rather than basic regular expressions (BRE's). The
re_format(7) manual page fully describes both formats.

how can be remove all white spaces fron begin of line using tr in bash

The Answer to your quesition is no. tr doesn't support deletion of specific patterns using regex.
The purpose of tr is different - man tr

If you want to use sed:

sed -i -e 's/^[ \t]*//' file.txt


Related Topics



Leave a reply



Submit