Remove whitespace before a field using AWK

自作多情 提交于 2019-12-12 17:35:15

问题


(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;
 }  

Kind regards in advance


回答1:


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;
}




回答2:


awk '{sub(/^[ \t]+/, ""); print}'

This is from the famous awk 1 liners list, can be found here: http://student.northpark.edu/pemente/awk/awk1line.txt




回答3:


This strikes me as being a case of 'wrong tool for the job'. I'd use sed`:

sed 's/^[ <tab>]*//' sample.out

Now, if the problem is all about the inner-most details of awk, this may be no help; if the problem is to get spaces removed, it is quicker and (at least arguably) simpler.



来源:https://stackoverflow.com/questions/409060/remove-whitespace-before-a-field-using-awk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!