Home > OS >  How to assign & display index number for everyline, and choose first field value through index numbe
How to assign & display index number for everyline, and choose first field value through index numbe

Time:01-17

I have this bash script:

#!/usr/bin/env bash
job=`cat example.txt`
lines=`cat example.txt | cut -d " " -f1`
for i in ${!lines[@]}; do echo "$i\t" ${job[$i]}; done
PS3="Select desired job-id to check current status: ENTER HERE!!! => "
select id in "${lines[@]}"; do echo "you have selected ${id}" ; echo "looking into ${id}" ; break
done

with this example.txt file:

53763958  4.01005  my_job  me_userid  r    2023-01-13T07:39:10.821  1
53763959  0.00000  your_job  you_userid  hqw  2023-01-13T07:37:29.525  1
53763961  0.00000  his_job  he_userid  hqw  2023-01-13T07:37:29.923  1
53763929  0.00000  her_job  her_userid  qw   2023-01-13T07:28:56.918  1

results in:

1) 53763958
53763959
53763961
53763929
Select desired job-id to check current status: ENTER HERE!!! => 1
you have selected 53763958
53763959
53763961
53763929
looking into 53763958
53763959
53763961
53763929

My desired result is:

1) 53763958  4.01005  my_job  me_userid  r    2023-01-13T07:39:10.821  1
2) 53763959  0.00000  your_job  you_userid  hqw  2023-01-13T07:37:29.525  1
3) 53763961  0.00000  his_job  he_userid  hqw  2023-01-13T07:37:29.923  1
4) 53763929  0.00000  her_job  her_userid  qw   2023-01-13T07:28:56.918  1

you have selected: 53763958-my_job

I will choose x) index and first field value (53763958 in this example) must be choosen as a vaiable for next command (echo "looking into ${id}")

CodePudding user response:

First, put the entire file's contents into an array.

readarray -t lines < example.txt

and use this array to build the menu. You won't extract the first field until after a choice is made.

PS3="Select desired job-id to check current status: ENTER HERE!!! => "
select job in "${lines[@]}"; do 
    id=$(echo "$job" | cut -d " " -f1)
    echo "you have selected ${id}"
    echo "looking into ${id}"
    break
done
  •  Tags:  
  • bash
  • Related