Search code examples
linuxformattingawkwhitespace

Remove whitespace before a field using AWK


(Almost exact duplicate of Keeping original format POST passing through AWK submitted by same person.)

I have a simple question pertaining to gawk, illustrated below:

  1 int blah (void)
  2 {
  3         if (foo) {
  4                 printf ("blah\n");
  5         }       
  6         return 0;
  7 }  

Using the following gawk code - using gensub() to maintain original formatting:

 gawk '{ print gensub($1, "\t", 1) }' ./sample_code.out

     int blah (void)
     {
             if (foo) {
                     printf ("blah\n");
             }       
             return 0;
     }  

How can I use gawk or awk (maybe with regular expressions) to remove previous whitespace before field $1 (^)

Illustrated below:

 int blah (void)
 {
         if (foo) {
                 printf ("blah\n");
         }       
         return 0;
 }  

Solution

  • This works, but in the knowledge that you'll always want to strip 3 spaces.

    vinko@parrot:~$ cat foo.c
      1 int blah (void)
      2 {
      3         if (foo) {
      4                 printf ("blah\n");
      5         }
      6         return 0;
      7 }
    
    vinko@parrot:~$ gawk '{ print gensub(/^   /,"",1,gensub($1, "", 1)) }' foo.c    
    int blah (void)
    {
            if (foo) {
                    printf ("blah\n");
            }
            return 0;
    }