TransWikia.com

How do I get values of certain row by column names?

Ask Ubuntu Asked on December 27, 2021

This is the output for the command aws iam get-credential-report --query 'Content' --output text | base64 -d from this output how to grep the values of access_key_1_active and access_key_1_last_rotated of user username mahi-user?

user,arn,user_creation_time,password_enabled,password_last_used,password_last_changed,password_next_rotation,mfa_active,access_key_1_active,access_key_1_last_rotated,access_key_1_last_used_date,access_key_1_last_used_region,access_key_1_last_used_service,access_key_2_active,access_key_2_last_rotated,access_key_2_last_used_date,access_key_2_last_used_region,access_key_2_last_used_service,cert_1_active,cert_1_last_rotated,cert_2_active,cert_2_last_rotated
<root_account>,arn:aws:iam::929815623526:root,2020-04-13T07:32:24+00:00,not_supported,2020-07-24T04:03:37+00:00,not_supported,not_supported,false,true,2020-07-17T05:20:25+00:00,N/A,N/A,N/A,true,2020-06-26T10:12:43+00:00,2020-07-24T06:20:00+00:00,us-east-1,s3,false,N/A,false,N/A
mahi-user,arn:aws:iam::929815623526:user/mahi-user,2020-07-21T06:21:51+00:00,true,no_information,2020-07-21T06:21:53+00:00,N/A,false,true,2020-07-21T06:21:53+00:00,N/A,N/A,N/A,false,N/A,N/A,N/A,N/A,false,N/A,false,N/A

One Answer

You can use awk in the following way (source):

1st create awk script as this:

$ cat usr-col.awk
BEGIN { FS = "," }
NR==1 {
    for (i=1; i<=NF; i++) {
        ix[$i] = i
    }
}
NR>1 {
    if ( $1 ~ usr ) print $ix[c1], $ix[c2]
}

where:

  • FS = "," will set the field separator to ,;
  • NR==1 means if it is the first row of the table;
  • the for loop will create associative array: ix[column name] = <column number>;
  • NR>1 means any row of the table which number is bigger than 1;
  • if ( $1 ~ usr ) will provide output if the first field of a line match to the value of the variable usr (the value could be regex);
  • print $ix[c1] will output the value of the field mummer equal to the column name provided by the value of the variable c1...

2nd use the script in this way:

aws ... | awk -f usr-col.awk usr='mahi-user' c1='access_key_1_active' c2='access_key_1_last_rotated'

I do not have the aws command, so in order to perform a test I've stored the provided output in a file, also I've added few lines with data for other users. Here is one of the tests I made - it searches data for multiple users (mahi-user and spas) within two arbitrary columns (arn and password_enabled):

$ cat aws.output | awk -f usr-col.awk usr='mahi-user|spas' c1='arn' c2='password_enabled'
arn:aws:iam::929815623526:user/mahi-user true
arn:aws:iam::929815623526:user/spas false

Answered by pa4080 on December 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP