LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Unwanted blank after word deletion (http://www.linuxquestions.org/questions/programming-9/unwanted-blank-after-word-deletion-4175432699/)

danielbmartin 10-17-2012 09:47 AM

Unwanted blank after word deletion
 
Have: a file of lines containing blank-delimited words, such as ...
Code:

one two three four five
Want: a file with the second word in each line removed, such as:
Code:

one three four five
cut does this nicely:
Code:

cut -d" " -f1,3-
However, this awk ...
Code:

awk '{$2=""; print}'
... produces this ...
Code:

one  three four five
There are two blanks between "one" and "three". Is there a way to code an awk to generate output with only one blank?

Daniel B. Martin

kabamaru 10-17-2012 11:38 AM

Code:

{ for (i=1; i<NF; i++)
  if (i!=2)
    printf("%s ", $i)
  printf("%s\n", $i)
}


kabamaru 10-17-2012 11:54 AM

Changed it a bit. More compact, and removed trailing space.

grail 10-17-2012 12:12 PM

How about:
Code:

awk 'sub(" "$2,"")' file

kabamaru 10-17-2012 12:16 PM

@grail

Nice trick ! Must read about awk functions.

danielbmartin 10-17-2012 12:17 PM

Quote:

Originally Posted by grail (Post 4808325)
How about:
Code:

awk 'sub(" "$2,"")' file

Sweet! Thank you! SOLVED!

Daniel B. Martin

firstfire 10-17-2012 01:43 PM

Hi.

grail's approach have this little problem:
Code:

$ echo 'one two three four three five' |  awk '{sub(" "$5, "")} 1'
one two four three five

When there are repeated fields, it actually removes first occurrence of the field, not necessarily a given one. In this example third field is removed instead of fifth (which contains same text as 3rd).

I myself yet to discover an elegant way to do this though.

EDIT:
Code:

$ echo 'one two three four five' |  awk '{$2=""; $0=$0; $1=$1} 1'
one three four five

which is equivalent to
Code:

$ echo 'one two three four five' |  awk '{$2=""; gsub(" +", " ")} 1'
one three four five

This way all extra spaces are lost, which may be undesirable.

BTW, just for fun, this also prints on a terminal what you want :)
Code:

$ echo 'one two three four five' |  awk '{$2="\b"} 1'
one three four five



All times are GMT -5. The time now is 07:12 PM.