Trying to remove leading spaces

OS : RHEL 6.7
Shell : bash

I am trying to remove the leading the spaces in the below file

$ cat pattern2.txt
  hello1
hello2
   hello3
     hello4

Expected output is shown below.

$ cat pattern2.txt
hello1
hello2
hello3
hello4

I tried using %s/[ ]*^//g command

If I understand correctly, [ ]*^ means zero or more occurences of blank spaces as the first character

But, I get the below error in Linux's vim editor

E486: Pattern not found: [ ]*^

Any idea why this command is not working ? Any workaround to get the leading spaces removed in vi (VIM) editor

To specify ex (or ed ) commands in vi , you precede the ex command with a : ; not with a % . The ex substitute command s/[ ]*^//g is a request to replace string of 0 or more <space> characters that are followed by the start of a line with nothing and to repeat that operation for every portion of each input line that matches that pattern. (Since there can never be anything on a line before the start of that line, there will never be any matches.)

To remove leading spaces from every line in a file you are editing in vi , try the command:

:g/^ [ ]*/s///
1 Like
:1,$ s/^ *//
1 Like