0

I wish to delete one column of my data in awk but what I found is using command like $column_A="". Is column_A really deleted in this way?

For example, I wish to delete the second column and I found a solution: awk 'BEGIN{FS="\t";OFS="\t"}!($2="")' which print the result like: $1^0^0$3. It seems that it is the content of the second column is deleted but the second column.

pnuts
  • 58,317
  • 11
  • 87
  • 139
Xiang Zhang
  • 241
  • 1
  • 7

2 Answers2

2

after reading dev-null's comment, I got idea what are you asking...

My answer is: it depends on how do you define "a column is deleted".

see this example:

kent$  echo "foo,bar,blah"|awk -F, -v OFS="," '{$2="";print}'
foo,,blah

kent$  echo "foo,bar,blah"|awk -F, -v OFS="," '{print $1,$3}'
foo,blah

You see the difference? If you set the $x="" The column is still there, but it becomes an empty string. So the FS before and after stay. If this is what you wanted, it is fine. Otherwise just skip outputing the target column, like the 2nd example shows.

Kent
  • 189,393
  • 32
  • 233
  • 301
  • Yes, the second example is just what I want but the problem is there may be too many columns to remain while some other columns to be deleted. For example, there are total 50 columns while $2, $10 are supposed to be deleted. I cannot just type each column. But you give an idea. I will search for method to print columns with skipping particular ones. Thank you! – Xiang Zhang Nov 20 '15 at 11:00
  • @XiangZhang you can make use of `printf in for loop` to achieve it. – Kent Nov 20 '15 at 11:05
  • @kent, I'm embarrassed to say it was me, and I have no memory of doing it! I'm only knowing it because I saw a `-1` adjustment to my rep and followed it here --- I obviously mis-clicked without even realizing it. Please make any kind of an edit to your answer so that SO will let me undo the downvote. – jas Nov 23 '15 at 20:42
0

I would use cut for that:

cut -d$'\t' -f1,3- file

-f1,3- selects the first field, skips field 2 and then selects fields 3 to end.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266