Atomiklan
Atomiklan

Reputation: 5434

awk two columns into a bash for loop

Please help!

I have a little bit of a time sensitive issue here and so I am turning to Stackoverflow in the hope that I can get a fairly quick reply. I'm not a bash expert, especially when having to think quickly. I am trying to awk in two columns from a user database into an OpenStack API. The database (flat file I created) is really simple. It looks something like this:

| ID | username | True |

The database is pretty large so I am trying to loop through this. Here is the command I am trying to run:

for user in $(cat users.txt); do keystone user-role-add --user $user --role blah --tenant $tenant; done

This works great assuming users.txt list had a single username on each line.

I need to modify this command to pull the username out of users.txt for $user and also pull the corresponding ID out of users.txt for $tenant

* SOLUTION *

while read line;do
  tenant=$(echo $line|awk '{print $2}')
  user=$(echo $line|awk '{print $4}')
  keystone user-role-add --user $user --role blah --tenant $tenant
done <users.txt

Thanks again!

Upvotes: 6

Views: 4998

Answers (3)

qaziqarta
qaziqarta

Reputation: 1944

awk -F' *[|] *' \
    '{print "keystone user-role-add --user \47" $3 "\47 --role blah --tenant \47" $2 "\47"}' users.txt \
| bash

Explanation line by line:

  1. Pass the file through awk using pipe with zero or more leading/trailing spaces as a delimiter.
  2. For each line of file users.txt print the required command as string. $2 and $3 mean second and third field from delimited file. \47 will be interpolated to a single quote in the output, in case we have spaces in values.
  3. Pipe the printed commands from the previous step to bash for execution.

Upvotes: 0

albeus
albeus

Reputation: 316

This way avoids using awk, it shoud be more optimized:

  while read id username tenant; do
      echo "---DEBUG --- id=${id} username=${username} tenant=${tenant}"
      # do other action here
      # calling variables as in DEBUG line above
  done <users.txt

Upvotes: 7

smokes2345
smokes2345

Reputation: 190

You probably want something like...

while read line;do
  id=$(echo $line|awk '{print $2}')
  username=$(echo $line|awk '{print $4}')
  bool=$(echo $line|awk '{print $6}')
  # do other
  # action here
done <users.txt

Upvotes: 3

Related Questions