Reputation: 937
I'm pretty new at unix in general and I'm having a tough time trying to figure out how to accomplish something I'm trying to do. For a record looking like this:
Name:Alice,ID:2368, Hometown:columbus,bithday:03/11/1988
Name:Bob,ID:2568,Hometown:New York,bithday:04-24-1985
Name:Ted,ID:2368, Hometown:Portland,bithday:06-11-1992
Name:Mark, ID:2218, Hometown:Palo Alto,bithday:04-23-1984
Name:Xiao, ID:2571, hometown:Carson,bithday:07/06/1975
Name:Rain, ID:0264, hometown:little stone,bithday:11-09-1982
Name:Susuan, ID:1261, Hometown:Menlo park,bithday:12-13-1989
Name:Zack, ID:1594, Hometown:columbus,bithday:02-04-1984
I want to remove any column ending in a colon and at the same time end up with no commas.
So a certain line might look like this:
Mark 2218 Palo Alto 04-23-1984
I've looked at a few examples of using awk and this is my idea so far:
awk 'BEGIN {FS=":"} ; {for (i=1; i<=NF; i++)
My thought process is to basically loop through each line and say, "If the field ends in a colon then remove it and look for the next field ending in a colon, go to the next line and so on. I just am not sure how to do this and I'm struggling because all the tutorials I've seen so far don't do anything similar to this. If anyone could help me out I would sincerely appreciate it! I would be grateful for any help at all.
Upvotes: 1
Views: 1223
Reputation: 246764
The awk field separator can be a regular expression (in GNU awk anyway), so set the FS to be either a comma or a colon and then print every other field:
awk -v FS='[,:]' '{for(i=2; i<=NF; i+=2) {printf "%s ", $i}; print ""}'
Given your sample input, you get:
Alice 2368 columbus 03/11/1988
Bob 2568 New York 04-24-1985
Ted 2368 Portland 06-11-1992
Mark 2218 Palo Alto 04-23-1984
Xiao 2571 Carson 07/06/1975
Rain 0264 little stone 11-09-1982
Susuan 1261 Menlo park 12-13-1989
Zack 1594 columbus 02-04-1984
Upvotes: 1
Reputation: 203229
$ cat file
Name:Mark, ID:2218, Hometown:Palo Alto,bithday:04-23-1984
$ awk '{sub(/^[^:]*:/,""); gsub(/,[^:]+:/," ")}1' file
Mark 2218 Palo Alto 04-23-1984
$ sed -e 's/^[^:]*://' -e 's/,[^:][^:]*:/ /g' file
Mark 2218 Palo Alto 04-23-1984
Upvotes: 3