web-dev-qa-db-fra.com

Puis-je supprimer un champ dans awk?

C'est test.txt:

0x01,0xDF,0x93,0x65,0xF8
0x01,0xB0,0x01,0x03,0x02,0x00,0x64,0x06,0x01,0xB0
0x01,0xB2,0x00,0x76

Si je cours awk -F, 'BEGIN{OFS=","}{$2="";print $0}' test.txt le résultat est:

0x01,,0x93,0x65,0xF8
0x01,,0x01,0x03,0x02,0x00,0x64,0x06,0x01,0xB0
0x01,,0x00,0x76

Les 2 $ n'ont pas été supprimés, il est venu de devenir vide. J'espère que lors de l'impression de 0 $, que le résultat est:

0x01,0x93,0x65,0xF8
0x01,0x01,0x03,0x02,0x00,0x64,0x06,0x01,0xB0
0x01,0x00,0x76
19
Edward

En utilisant AWK de manière sans regex, la possibilité de choisir la ligne sera supprimée:

awk '{ col = 2; n = split($0,arr,","); line = ""; for (i = 1; i <= n; i++) line = line ( i == col ? "" : ( line == "" ? "" : ","  ) arr[i] ); print line }' test.txt

Pas à pas:

{
col = 2    # defines which column will be deleted
n = split($0,arr,",")    # each line is split into an array
                         # n is the number of elements in the array

line = ""     # this will be the new line

for (i = 1; i <= n; i++)   # roaming through all elements in the array
    line = line ( i == col ? "" : ( line == "" ? "" : "," ) arr[i] )
    # appends a comma (except if line is still empty)
    # and the current array element to the line (except when on the selected column)

print line    # prints line
}
1
Pedro Maimere