Reputation: 11
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 3
4 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?
Upvotes: 1
Views: 144
Reputation: 743
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)
Upvotes: 2
Reputation: 34024
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
Upvotes: 1
Reputation: 21
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.
Upvotes: 1