How to use a variable in an awk expression

后端 未结 3 1538
隐瞒了意图╮
隐瞒了意图╮ 2021-01-20 21:31

I\'m trying to make this command:

sed bla bla filename | awk \'{printf \"%s %s_entry_%.3f %.3f %.3f %.3f\",$1,$3,$4,$5,$6,$7}\'

But the thi

相关标签:
3条回答
  • 2021-01-20 21:53

    you can use -v option of awk to pass in variable from the shell

    #!/bin/bash    
    awk -v values="${values}" '{gsub("blah","replace");printf "%s %s_entry_"values ....}' file
    

    the gsub() function is to replace what you have with that sed command. So just one awk command will do. sed is redundant in this case (and most other cases where awk is used)

    0 讨论(0)
  • 2021-01-20 21:54

    If you mean that values is a shell variable, then this will work:

    sed bla bla filename | awk '{printf "%s %s_entry_"ENVIRON["values"],$1,$3,$4,$5,$6,$7}'
    
    0 讨论(0)
  • 2021-01-20 21:57

    Easiest to use actual awk variables:

    sed bla bla filename | awk -v values="$values" '{printf "%s %s_entry_"values,$1,$3,$4,$5,$6,$7}'
    

    Or with bash:

    awk -v values="$values" '{printf "%s %s_entry_"values,$1,$3,$4,$5,$6,$7}' <(sed bla bla filename)
    
    0 讨论(0)
提交回复
热议问题