for loop in bash to get more than 1 variables to u

2019-08-15 16:30发布

I have one text file and I need to get 2 variables from the same text and put them in one command like

for i in `cat TEXT | grep -i UID | awk '{print($2)}'` && 
x in `cat TEXT | grep -i LOGICAL | awk '{print($4)}'`
do 
  echo "naviseccli -h 10.1.1.37 sancopy -create -incremental -name copy_$i -srcwwn $x -destwwn xxxxxxxxxxxxxxxxxxxxxx -verify -linkbw 2048" >> OUTPUT
done

is there any possible way to accomplish that am storage admin and need to do tons of commands so i need to get this script to do it

标签: linux bash
4条回答
劳资没心,怎么记你
2楼-- · 2019-08-15 17:04

You could make use of file descriptors. Moreover, your cat, grep, awk command could be combined into a single awk command:

exec 5< <(awk '{IGNORECASE=1}/UID/ {print $2}' TEXT)
exec 6< <(awk '{IGNORECASE=1}/LOGICAL/ {print $4}' TEXT)
while read i <&5 && read x <&6
do
  echo command $i $x         # Do something with i and x here!
done
查看更多
不美不萌又怎样
3楼-- · 2019-08-15 17:14

Perform the cat operations first and save the result into two arrays. Then you can iterate with an index over one array and use the same index to also access the other one.

See http://tldp.org/LDP/abs/html/arrays.html about arrays in bash. Especially see the section "Example 27-5. Loading the contents of a script into an array".

With that resource you should be able to both populate your arrays and then also process them.

查看更多
男人必须洒脱
4楼-- · 2019-08-15 17:16

Since your words don't have spaces in them (by virtue of the use of awk), you could use:

paste <(grep -i UID     TEXT | awk '{print($2)}') \
      <(grep -i LOGICAL TEXT | awk '{print($4)}') |
while read i x
do 
  echo "naviseccli -h 10.1.1.37 sancopy -create -incremental -name copy_$i -srcwwn" \
       "$x -destwwn xxxxxxxxxxxxxxxxxxxxxx -verify -linkbw 2048" >> OUTPUT
done

This uses Process Substitution to give paste two files which it pieces together. Each line will have two fields on it, which are read into i and x for use in the body of the loop.

Note that there is no need to use cat; you were eligible for a UUOC (Useless Use of cat) award.

查看更多
虎瘦雄心在
5楼-- · 2019-08-15 17:21

Imma take a wild guess that UID and LOGICAL must be on the same line in your incoming TEXT, in which case this might actually make some sense and work:

cat TEST | awk '/LOGICAL/ && /UID/ { print $2, $4 }' | while read i x
do 
  echo "naviseccli -h 10.1.1.37 sancopy -create -incremental -name copy_$i -srcwwn" \
       "$x -destwwn xxxxxxxxxxxxxxxxxxxxxx -verify -linkbw 2048"
done
查看更多
登录 后发表回答