How to combine two pieces of data?

Data redisin the demo file aaa:

million:relive:2270371,18,1
million:relive:user:49976159,27:8,340|2018-01-26 20:25:00
million:relive:stage:22,6,1

As a result, an additional column is added based on the thrid part of the key redis:

uid,million:relive:2270371,18,1
user,million:relive:user:49976159,27:8,340
stage,million:relive:stage:22,6,1

I can generate the first column using:

awk -F":" '{print $3}' aaa | awk '{if($0 ~ /^[0-9,]+?$/) print "uid"; else print $0}'

And the second part:

awk -F"|" '{print $1}' aaa

How to combine two parts and can they be made in one sentence?

+4
source share
3 answers
$ awk -F':' '{sub(/\|.*/,"");print ($3~/^[0-9]+,/?"uid":$3)","$0}' aaa
uid,million:relive:2270371,18,1
user,million:relive:user:49976159,27:8,340
stage,million:relive:stage:22,6,1

The above single line liner will help you. First, he deleted the part |......, then added the key depending on$3

+3
source

You can use the following command awk:

$awk -F":" '/\|/{sub(/\|.*/,"",$0)}{if($3 ~ /^[0-9,]+?$/)printf "uid,";else printf $3",";print $0}' aaa

This will lead to the following conclusion:

uid,million:relive:2270371,18,1
user,million:relive:user:49976159,27:8,340
stage,million:relive:stage:22,6,1
+2
source

Below is another one awk-line in the repertoire of your decision

$ awk -v OFS=":" '{sub(/\|.*$/,"");FS=":";sub(/^/,match($3,/^(user|stage)$/,a)?a[1]",":"uid,",$1)}1' file

uid,million:relive:2270371,18,1
user,million:relive:user:49976159,27:8,340
stage,million:relive:stage:22,6,1
+2
source

Source: https://habr.com/ru/post/1692954/


All Articles