Set variable in current shell from awk

后端 未结 7 1893
花落未央
花落未央 2020-12-29 05:40

Is there a way to set a variable in my current shell from within awk?

I\'d like to do some processing on a file and print out some data; since I\'ll rea

相关标签:
7条回答
  • 2020-12-29 06:14

    A warning for anyone trying to use declare as suggested by several answers.

    eval does not have this problem.

    If the awk (or other expression) provided to declare results in an empty string then declare will dump the current environment. This is almost certainly not what you would want.

    eg: if your awk pattern doesn't exist in the input you will never print an output, therefore you will end up with unexpected behaviour.

    An example of this....

     unset var
     var=99
     declare $( echo "foobar" | awk '/fail/ {print "var=17"}' )
     echo "var=$var"
    var=99
    The current environment as seen by declare is printed
    and $var is not changed
    

    A minor change to store the value to set in an awk variable and print it at the end solves this....

     unset var
     var=99
     declare $( echo "foobar" | awk '/fail/ {tmp="17"} END {print "var="tmp}' )
     echo "var=$var"
    var=
    This time $var is unset ie: set to the null string var=''
    and there is no unwanted output.
    

    To show this working with a matching pattern

     unset var
     var=99
     declare $( echo "foobar" | awk '/foo/ {tmp="17"} END {print "var="tmp}' )
     echo "var=$var"
    var=
    This time $var is unset ie: set to the null string var=''
    and there is no unwanted output.
    
    0 讨论(0)
提交回复
热议问题