Shell Script - save substring to variable
A really simple shell script question. I have a file with something like this:
var "aaaaa"
var "bbbbb"
...
Now, ho开发者_C百科w can I assign the string in quotes to a variable? This is what I have now (but I'm missing the assign part...):
while read line
do
echo $line | cut -d" " -f3
done
which prints what I want... how do I save it to a variable?
Thanks
my_var=$(echo $line | cut -d" " -f3)
You need to execute the command. That is what the $() is for.
Depends on a shell.
Bourne and derivatives, you do
my_var_name=expression
C shell and derivatives, you do
setenv my_var_name expression
If you want to save the output of a command (e.g. "cut xyz"), you use backticks operator as your expression:
my_var_name=`echo $line | cut -d" " -f3`
I think that bash also supports $() but not sure of a difference from backticks - see section 3.4.5 from http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html
you don't have to use external cut command to "cut" you strings. You can use the shell, its more efficient.
while read -r a b
do
echo "Now variable b is your quoted string and has value: $b"
done <"file"
Or
while read -r line
do
set -- $line
echo $2
done <"file"
精彩评论