Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove preceding spaces before non space text begins + regex + sed +

Tags:

regex

bash

sed

How do I remove the preceding spaces before 809 in the output of my echo??

here is my sample:

$ echo '   809 23/Dec/2008:19:20'
   809 23/Dec/2008:19:20
^^^3 spaces here preceding the 809    

I can remove 3 or 4 spaces using sed:

        ...4 spaces here   
$ echo '    809 23/Dec/2008:19:20' | sed 's/^.\{3\,4\}//'
809 23/Dec/2008:19:20
0 spaces here preceding the 809    

But what I want is my sed command to work on anything greater than 3

        .....5 spaces here
$ echo '     809 23/Dec/2008:19:20' | sed 's/^.\{3\,4\}//'
 809 23/Dec/2008:19:20
^1 spaces here preceding the 809    

Ho do I write my regex in the sed to remove 3 or more spaces preceding 809?

like image 849
HattrickNZ Avatar asked Dec 24 '22 09:12

HattrickNZ


2 Answers

If you want to remove 3 or more spaces at the start use

sed 's/^[[:blank:]]\{3,\}//'

Details

  • ^ - start of input
  • [[:blank:]]\{3,\} - 3 or more consecutive occurrences of any horizontal whitespace.

If you need to remove 3+ spaces at the start before a specific value, say, 809, just add that value to the regex and replacement pattern:

sed 's/^[[:blank:]]\{3,\}809/809/'

or use a capturing group and placeholder:

sed 's/^[[:blank:]]\{3,\}\(809\)/\1/'

enter image description here

like image 116
Wiktor Stribiżew Avatar answered May 19 '23 23:05

Wiktor Stribiżew


xargs frees you from thinking about regular expressions.

$ echo '   809 23/Dec/2008:19:20' | xargs
809 23/Dec/2008:19:20

It's a more or less unconventional trick of xargs. This tool is meant to be used to build up commands with long argument lists. From man page:

xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command

However, it a part of the preprocess that white space will be trimmed, before sending to subsequent command. In this case, there isn't subsequent command, and therefore xargs just send the argument as it is, modulo with the spaces trimmed, to standard output, which does exactly what you are asking for.

like image 22
Jason Hu Avatar answered May 19 '23 23:05

Jason Hu