AWK if length statement append

2019-07-15 05:13发布

I am trying to fix a problem of missing data in a csv file. The column, that should be null, is lacking a double field separator to maintain the csv structure. The example below illustrates what I mean:

 1@Sunshine@2/M@L@JRVel@215@WAW
 2@Pass@2/J@L1@JAvar@218@JKDes
 3@Solo@2/K@JRosa@218@WAW
 4@Bomber@2/D@L1@JLOrt@218@GCCon
 5@SmokingCandy@2/Y@L1@MFco@218@SMAs
 6@BigBound@2/H@L1@JCast@218@SMAs
 7@ShootBunies@2/H@L@DLPar@218@DKo

As you can see, in the third row, fourth column, there is no "L" or "L1", instead it's "JRosa". This causes incorrect formating of a mysql database down the road. What I would like to do is use an AWK if statement to append another delimiter infront of "JRosa". So far I have half a code and no idea where to go. I was thinking it would be something that starts like:

awk -F@ '{if(length($4) > 4) print "@"$4}'

Which just printouts:

@JRosa

I'm hoping to find a solution that results in:

1@Sunshine@2/M@L@JRVel@215@WAW
2@Pass@2/J@L1@JAvar@218@JKDes
3@Solo@2/K@@JRosa@218@WAW
4@Bomber@2/D@L1@JLOrt@218@GCCon
5@SmokingCandy@2/Y@L1@MFco@218@SMAs
6@BigBound@2/H@L1@JCast@218@SMAs
7@ShootBunies@2/H@L@DLPar@218@DKo

Does anybody know the correct formating after the if statement that can be used to append the input data?

1条回答
聊天终结者
2楼-- · 2019-07-15 05:47

Just add an extra "@" at the end of the 3rd field if there's less than 7 fields on the line:

$ awk 'BEGIN{FS=OFS="@"} NF<7{$3=$3FS} 1' file
 1@Sunshine@2/M@L@JRVel@215@WAW
 2@Pass@2/J@L1@JAvar@218@JKDes
 3@Solo@2/K@@JRosa@218@WAW
 4@Bomber@2/D@L1@JLOrt@218@GCCon
 5@SmokingCandy@2/Y@L1@MFco@218@SMAs
 6@BigBound@2/H@L1@JCast@218@SMAs
 7@ShootBunies@2/H@L@DLPar@218@DKo
查看更多
登录 后发表回答