从一个awk命令设置多个变量?

时间:2012-03-02 07:52:06

标签: bash awk

这是一个非常常见的脚本:

#!/bin/bash

teststr="col1 col2"

var1=`echo ${teststr} | awk '{print $1}'`
var2=`echo ${teststr} | awk '{print $2}'`

echo var1=${var1}
echo var2=${var2}

但是我不喜欢这个,特别是当有更多的字段需要解析时。 我想应该有更好的方式:

(var1,var2)=`echo $ {teststr} | awk'{print $ 1 $ 2}' (在我的想象中)

是吗?是这样吗? 感谢您帮助提高效率并节省一些CPU电量。

3 个答案:

答案 0 :(得分:7)

这可能对您有用:

var=(col0 col1 col2)
echo "${var[1]}"
col1

答案 1 :(得分:0)

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阵列文档:http://tldp.org/LDP/abs/html/arrays.html

答案 2 :(得分:0)

您还可以使用内置的shell <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> <div class="row"> <div class="col-md-6"> <div class="textarea_before forScroll" > Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> </div> </div> <div class="col-md-6"> <div class="textarea_after forScroll" > Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> Lorem <br> </div> </div> </div>将分隔的空格(或更准确地说,set分隔的空格)放入变量IFS$1等, >

$2