Is there a way to completely delete fields in awk, so that extra delimiters do not print?

后端 未结 9 1071
醉话见心
醉话见心 2020-12-20 12:52

Consider the following command:

$ gawk -F"\\t" "BEGIN{OFS=\\"\\t\\"}{$2=$3=\\"\\"; p         


        
相关标签:
9条回答
  • 2020-12-20 13:12

    One way could be to remove fields like you do and remove extra spaces with gsub:

    $ awk 'BEGIN { FS = "\t" } { $2 = $3 = ""; gsub( /\s+/, "\t" ); print }' input-file
    
    0 讨论(0)
  • 2020-12-20 13:14

    The only way I can think to do it in Awk without using a loop is to use gsub on $0 to combine adjacent FS:

    $ echo {1..10} | awk '{$2=$3=""; gsub(FS"+",FS); print}'
    1 4 5 6 7 8 9 10
    
    0 讨论(0)
  • 2020-12-20 13:14
    echo one two three four five six|awk '{
    print $0
    is3=$3
    $3=""
    print $0
    print is3
    }'
    

    one two three four five six

    one two four five six

    three

    0 讨论(0)
  • 2020-12-20 13:17

    Well, if the goal is to remove the extra delimiters, then you can use tr on Linux. Example:

    $ echo "1,2,,,5" | tr -s ','
    
    1,2,5
    
    0 讨论(0)
  • 2020-12-20 13:19

    You can't delete fields in the middle, but you can delete fields at the end, by decrementing NF.

    So you can shift all the later fields down to overwrite $2 and $3 then decrement NF by two, which erases the last two fields:

    $ echo 1 2 3 4 5 6 7 | awk '{for(i=2; i<NF-1; ++i) $i=$(i+2); NF-=2; print $0}'
    1 4 5 6 7
    
    0 讨论(0)
  • 2020-12-20 13:19

    In the addition of the answer by Suicidal Steve I'd like to suggest one more solution but using sed instead awk.

    It seems more complicated than usage of cut as it was suggested by Steve. But it was the better solution because sed -i allows editing in-place.

    $ sed -i 's/\(.*,\).*,.*,\(.*\)/\1\2/' FILENAME
    
    0 讨论(0)
提交回复
热议问题