我试图用13个用逗号分隔的字段替换字符串中的字段。我既有要替换的位置,也有要在分离变量中给该位置的新值。使用bash。
#Original string:
THR=’0,0,0,0,0,0,0,0,0,0,0,0,0’
#Position I want to manipulate:
pos=’3’
#Value I want to write in the field "pos"
val=’8.73’
# What I'm trying to do:
echo $THR | awk -v chawk=$pos -v thrawk=$val -F',' '{ print; $chawk=$thrawk; print }'
THR应该是'0,0,8.73,0,0,0,0,0,0,0,0,0,0'
干杯
最佳答案
你已经差不多了,去掉前面的$
awk -v chawk=$pos -v thrawk=$val -F',' '{ print; $chawk=thrawk; print }' OFS=\. <<< $THR
0,0,0,0,0,0,0,0,0,0,0,0,0
0.0.8.73.0.0.0.0.0.0.0.0.0.0
把它恢复到变量THR
THR=0,0,0,0,0,0,0,0,0,0,0,0,0
THR=$(awk -v chawk=$pos -v thrawk=$val -F',' '{ $chawk=thrawk; print }' OFS=\. <<< $THR)
echo $THR
0.0.8.73.0.0.0.0.0.0.0.0.0.0
关于bash - AWK:在给定变量的位置和新值的情况下,用字符串替换字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19581105/