Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

remove specific field without changing field seperator

Status
Not open for further replies.

arunrr

Programmer
Oct 2, 2009
103
US
Input string ($INPUT) can be...

3,J Smith,Manager,121,207,197,16,0,61.42

or

3,J Smith,Manager,121,197,16,0,61.42

In the first case NF=9; In the second case NF=8.
I need to remove the 5th field if NF=9 and do nothing if NF=8.

I tried the following...

echo $INPUT | awk -F, '{if (NF==9) $5=""}1'

This does remove the field, but changes the field separator to a space from a ",". I need to keep the "," FS. Please help.

thanks,
AR
 
How about this;

Tested with nawk because I use Solaris;

nawk -F, 'BEGIN{OFS=","}{if (NF==9) $5=""}1' $INPUT > outfile

I'm no expert though, so I'm sure one of the bigger brains may have a cut down version for you.

Hope this helps.
Alan
 
Hi

[tt]$5=""[/tt] only replaces the value of the 5th field, but it remains there. AR's code seemed to work just because the less evident separators, but Alan's code should display clearly the 5th field with its new empty value. ( I mean, two consecutive separators after the 4th field. )

The way I know, has two steps :
[ul]
[li]shift all fields after the 5th to left with 1[/li]
[li]decrement the field count[/li]
[/ul]
Note that modifying the field count like this is not supported by some [tt]awk[/tt] implementations :
Code:
awk -F, -vOFS=',' 'NF==9{for(i=5;i<NF;i++)$i=$(i+1);NF--}1' /input/file
Or another, less elegant but more portable, also in two steps :
[ul]
[li]replace the 5th field with a ( hopefully unique ) placeholder[/li]
[li]replace the placeholder and the following field separator with nothing[/li]
[/ul]
Code:
awk -F, -vOFS=',' 'NF==9{$5="REMOVEME";sub(/REMOVEME,/,"")}1' /input/file
Tested with [tt]gawk[/tt] and [tt]mawk[/tt].

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top