Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

awk - How do I used sed to remove a whole column of data in unix?

I need some help with getting rid of all the driver names from the file using a sed command. I've tried multiple different commands but I cant get it to function properly.

Input:

Rank Country         Driver       Races Wins
1 [United_Kingdom] Lewis_Hamilton 264 94
2 [Germany] Sebastian_Vettel      254 53
3 [Spain] Fernando_Alonso         311 32
4 [Finland] Kimi_Raikkonen        326 21
5 [Germany] Nico_Rosberg          200 23

I've tried using cat f1.txt| sed -r 's/S+//3' but it does not keep the formatting I would like

what i would like it to do

Input:

Rank Country         Driver       Races Wins
1 [United_Kingdom]                 264 94
2 [Germany]                        254 53
3 [Spain]                          311 32
4 [Finland]                        326 21
5 [Germany]                        200 23
question from:https://stackoverflow.com/questions/65837198/how-do-i-used-sed-to-remove-a-whole-column-of-data-in-unix

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The easy way to do it is just replace $3 with spaces equal to the length of the field, e.g.

awk 'FNR > 1{s=sprintf("%*s", length($3) + 1, " "); sub($3,s)}1' drivers

The condition FNR > 1 simply skips the 1st line in the file to preserve all headings. +1 was added to the length of the 3rd field to match your exact output format.

Example Use/Output

$ awk 'FNR > 1{s=sprintf("%*s", length($3) + 1, " "); sub($3,s)}1' drivers
Rank Country         Driver       Races Wins
1 [United_Kingdom]                 264 94
2 [Germany]                        254 53
3 [Spain]                          311 32
4 [Finland]                        326 21
5 [Germany]                        200 23

Note: If your input file actually contains "Input:" at the beginning, then you would use:

awk 'NF == 5 && $1 ~ /^[0-9]/ {s=sprintf("%*s", length($3)+1, " "); sub($3,s)}1' drivers

Here the condition 'NF == 5 && $1 ~ /^[0-9]/ only applies the substitution to records (lines) with five-fields beginning with a digit.

Output

$ awk 'NF == 5 && $1 ~ /^[0-9]/ {s=sprintf("%*s", length($3)+1, " "); sub($3,s)}1' drivers
Input:

Rank Country         Driver       Races Wins
1 [United_Kingdom]                 264 94
2 [Germany]                        254 53
3 [Spain]                          311 32
4 [Finland]                        326 21
5 [Germany]                        200 23

I was unclear if that was actually part of the file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...