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.

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

1 Answer 1

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)}')
Sign up to request clarification or add additional context in comments.

2 Comments

You should also have quotes around s=*, to keep the shell from trying to expand that.
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 in the Help Center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.