bash 从一个 awk 命令设置多个变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9529791/
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
set multiple variables from one awk command?
提问by X.M.
This is a very common script:
这是一个非常常见的脚本:
#!/bin/bash
teststr="col1 col2"
var1=`echo ${teststr} | awk '{print }'`
var2=`echo ${teststr} | awk '{print }'`
echo var1=${var1}
echo var2=${var2}
However I dont like this, especially when there are more fields to parse. I guess there should be a better way like:
但是我不喜欢这个,尤其是当有更多的字段需要解析时。我想应该有更好的方法,例如:
(var1,var2)=`echo ${teststr} | awk '{print $1 $2}' (in my imagination)
(var1,var2)=`echo ${teststr} | awk '{print $1 $2}'(在我的想象中)
Is that so? Thanks for help to improve effeciency and save some CPU power.
是这样吗?感谢您帮助提高效率并节省一些 CPU 功率。
回答by potong
This might work for you:
这可能对你有用:
var=(col0 col1 col2)
echo "${var[1]}"
col1
回答by Hemant Patel
Bash has Array Support, We just need to supply values dynamically :)
Bash 有数组支持,我们只需要动态提供值:)
function test_set_array_from_awk(){
# Note : -a is required as declaring array
let -a myArr;
# Hard Coded Valeus
# myArr=( "Foo" "Bar" "other" );
# echo "${myArr[1]}" # Print Bar
# Dynamic values
myArr=( $(echo "" | awk '{print "Foo"; print "Bar"; print "Fooo-And-Bar"; }') );
# Value @index 0
echo "${myArr[0]}" # Print Foo
# Value @index 1
echo "${myArr[1]}" # Print Bar
# Array Length
echo ${#myArr[@]} # Print 3 as array length
# Safe Reading with Default value
echo "${myArr[10]-"Some-Default-Value"}" # Print Some-Default-Value
echo "${myArr[10]-0}" # Print 0
echo "${myArr[10]-''}" # Print ''
echo "${myArr[10]-}" # Print nothing
# With Dynamic Index
local n=2
echo "${myArr["${n}"]-}" # Print Fooo-And-Bar
}
# calling test function
test_set_array_from_awk
Bash Array Documentation : http://tldp.org/LDP/abs/html/arrays.html
Bash 阵列文档:http: //tldp.org/LDP/abs/html/arrays.html

