0

I have a linux script for selecting the node.

For example:

  4
  40*r13n15:40*r10n61:40*r11n18:40*r09n15

The correct result should be:

r13n15
r10n61
r11n18
r09n15

My linux script content is like:

hostNum=`bjobs -X -o "nexec_host" $1 | grep -v NEXEC`
hostSer=`bjobs -X -o "exec_host" $1 | grep -v EXEC`

echo $hostNum
echo $hostSer 

for i in `seq 1 $hostNum`
do
 echo $hostSer | awk -F ':' '{print '$i'}' | awk -F '*' '{print $2}'
done

But unlucky, I got nothing about node information.

I have tried:

echo $hostSer | awk -F ':' '{print "'$i'"}' | awk -F '*' '{print $2}'

and

echo $hostSer | awk -F ':' '{print '"$i"'}' | awk -F '*' '{print $2}'

But there are wrong. Who can give me a help?

tripleee
  • 175,061
  • 34
  • 275
  • 318
stack
  • 821
  • 1
  • 15
  • 28
  • 1
    i have tried How do I use shell variables in an awk script? (7 answers), but it is not ok again.echo $hostSer | awk -F ':' -v a=$i '{print a}' | awk -F '*' '{print $2}' – stack Jan 03 '20 at 09:43
  • The obvious and trivial bug is that you are missing the dollar sign before `{ print $a }` and similarly in `'{ print $'"$i"'}'` in your original code. But as all these answers suggest, you can easily avoid running Awk twice for this simple task. – tripleee Jan 03 '20 at 10:26

2 Answers2

3

One more awk:

$ echo "$variable" | awk 'NR%2==0'  RS='[*:\n]'
r13n15
r10n61
r11n18
r09n15

By setting the record separtor(RS) to *:\n , the string is broken into individual tokens, after which you can just print every 2nd line(NR%2==0).

Guru
  • 16,456
  • 2
  • 33
  • 46
2

You can use multiple separators in awk. Please try below:

h='40*r13n15:40*r10n61:40*r11n18:40*r09n15'
echo "$h"| awk -F '[:*]' '{ for (i=2;i<=NF;i+=2) print $i }' 

**edited to make it generic based on the comment from RavinderSingh13.

tripleee
  • 175,061
  • 34
  • 275
  • 318
Priya Agarwal
  • 462
  • 4
  • 11