Linux 将 AWK 结果分配给变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6031612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign AWK result to variable
提问by user739866
This should be pretty straightfoward and I don't know why I am struggling with it.
这应该很简单,我不知道为什么我要为此而苦苦挣扎。
I am running the following psql command from within a shell script in order to find out whether all indexes have been dropped before inserting data.
我正在 shell 脚本中运行以下 psql 命令,以便在插入数据之前找出是否所有索引都已删除。
INDEXCOUNT=$(psql -p $dbPort -U enterprisedb -d main_db -c "select Count(*) from all_indexes where index_schema = 'enterprisedb';")
At this point, INDEXCOUNT is equal to “COUNT ------- 0”
此时INDEXCOUNT等于“COUNT ------- 0”
Now if I echo the following line I get the result I want -
现在,如果我回应以下行,我会得到我想要的结果 -
echo $INDEXCOUNT | awk '{print }'
How do I assign the value of $INDEXCOUNT | awk ‘{print $3}'
to a variable to check it in an “IF” statement?
如何将 的值分配给$INDEXCOUNT | awk ‘{print $3}'
变量以在“IF”语句中检查它?
For example:
例如:
RETURNCOUNT=$INDEXCOUNT | awk '{print }'
采纳答案by nimrodm
The following works correctly on bash:
以下在 bash 上正常工作:
a=$(echo '111 222 33' | awk '{print ;}' )
echo $a # result is "33"
Another option would be to convert the string to an array:
另一种选择是将字符串转换为数组:
a="111 222 333"
b=($a)
echo ${b[2]} # returns 333
回答by Mayank
You can try this:
你可以试试这个:
RETURNCOUNT=`echo $INDEXCOUNT | awk '{print }'`
The idea is to include any shell command between backticks to get the result into a variable.
这个想法是在反引号之间包含任何 shell 命令,以将结果放入一个变量中。
回答by Dimitre Radoulov
Or you can directly use:
或者你可以直接使用:
${INDEXCOUNT##* }
回答by GoggiP
This might be easier to use for testing with if statement/
这可能更容易用于测试 if 语句/
INDEXCOUNT="111 222 333"
echo $INDEXCOUNT | awk '{if ( == 333) print }';