0

I have this code

echo "er453*tyu" |awk -v s=* '{print index($1,s)}'

The code prints 6. Now I want to reference 6 as a variable. E.g.

$position= "er453*tyu" |awk -v s=* '{print index($1,s)}'

Then use the variable position somewhere else in my code.

jww
  • 97,681
  • 90
  • 411
  • 885
cfugus
  • 3
  • 4
  • And the problem is? – tink Dec 09 '19 at 02:38
  • @tink read through the question! I want to reference echo "er453*tyu" |awk -v s=* '{print index($1,s)}' instead of echoing direct! – cfugus Dec 09 '19 at 02:43
  • 1
    Write complete specs/example data. As a variable WHERE? Inside the same awk script? In an encapsulating bash script? – tink Dec 09 '19 at 02:46

1 Answers1

0

You can execute any command and save its stdout to a variable in Bash like this:

position=$(echo "er453*tyu" | awk -v s=* '{print index($1,s)}')

Some notes:

  1. If er453*tyu is not supposed to expand, it would be safer to use single quotes around it. Same for s=*.
  2. If you are running this within a function, declare position as a local:
local position
position=$(echo "er453*tyu" | awk -v s=* '{print index($1,s)}')
Hubert Grzeskowiak
  • 15,137
  • 5
  • 57
  • 74
  • 1
    You should also have quotes around `s=*`, to keep the shell from trying to expand that. – Gordon Davisson Dec 09 '19 at 04:08
  • Obvious duplicates should be closed as duplicate, not given new answers, so there's a single canonical collection of answers for each distinct question that can be as effectively vetted and edited as possible. See the "Answer Well-Asked Questions" section of [How to Answer](https://stackoverflow.com/help/how-to-answer) in the Help Center. – Charles Duffy Dec 09 '19 at 04:37