问题
I'm writing a small bash script to get the number out of each file name. For example the file name helloworld1.txt
would produce 1
.
When attempting to set the output to the variable i
I get an error for each file.
line 5: 985.txt: Permission denied
If I just echo the command echo $f | tr -dc '[0-9]'
rather than assign it to a variable, everything is good.
#!/bin/bash
for f in *
do
i=`$f | tr -dc '[0-9]'` // Permission denied.
echo $i
done
回答1:
You have missed echo here. The line
i=`$f | tr -dc '[0-9]'`
should be
i=`echo $f | tr -dc '[0-9]'`
回答2:
The line in the loop without a subshell, pipe and additional process per file:
i=${f//[^0-9]/}
The parameter substitution removes all non-digits.
来源:https://stackoverflow.com/questions/23108816/bash-initialize-variable-to-output-of-command-permission-denied