1

I have a filename with several underscores:

nc_glals_3_4.mrc 

and there I can read out the values 3 and 4 with awk:

$ echo "nc_glals_3_4.mrc" | awk -F'[_.]' '{print$3$4}' 
34

But if I like to store 34 as a variable and recall the variable, it does not work:

$ variable=$("nc_glals_3_4.mrc" | awk -F'[_.]' '{print $3$4}')
-bash: nc_glals_3_4.mrc: command not found

$ variable="$("nc_glals_3_4.mrc" | awk -F'[_.]' '{print $3$4}')"
-bash: nc_glals_3_4.mrc: command not found

$ variable
-bash: variable: command not found

What's wrong?

2
  • variable=$(echo "nc_glals_3_4.mrc" | awk -F'[_.]' '{print $3$4}') Commented Dec 2, 2020 at 22:50
  • You need echo inside of $( . . . ) just like on the outside. Bash is attempting to run your string as a program Commented Dec 3, 2020 at 1:08

3 Answers 3

2

If the numbers you want to retain are always in the same position:

test@darkstar:~$ Filename="nc_glals_3_4.mrc"
test@darkstar:~$ awk -F'[_.]' '{print$3$4}' <<< $Filename
34
test@darkstar:~$ Numbers=$(awk -F'[_.]' '{print$3$4}' <<< $Filename)
test@darkstar:~$ echo $Numbers
34
test@darkstar:~$

But if the numbers are not always in the same position and you want to catch all numbers between underscores or between underscore and full stop no matter where they occour:

Numbers=$(awk -F'[_.]' '{for (i=0;i<=NF;i++) {if ($i~/^[0-9]+$/) {printf("%i", $i)}}}' <<< $Filename)
Sign up to request clarification or add additional context in comments.

Comments

1

If I understand your question:

variable=$(echo "nc_glals_3_4.mrc" | awk -F'[_.]' '{print $3$4}')

You need an echo in your command.... now '34' is stored into variable.

Comments

1

Just as you used echo on the command line, you also need to use echo in the sub-process call, eg:

# wrong:

$ variable=$("nc_glals_3_4.mrc" | awk -F'[_.]' '{print $3$4}')

# right:

$ variable=$(echo "nc_glals_3_4.mrc" | awk -F'[_.]' '{print $3$4}')

# or using here string:

$ variable=$(awk -F'[_.]' '{print $3$4}' <<< "nc_glals_3_4.mrc")

Then use echo again to display the variable's value:

$ echo "${variable}"
34

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.