2013-10-25 70 views
3

我試圖用字符串替換字段中的13個字段並用逗號分隔。我有我想要替換的位置和我想要在分離的變量中賦予該位置的新值。使用bash。AWK:用給定位置和變量中新值的字符串替換字段

#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'

乾杯

回答

2

你得這近,取出$盈的$thrawk

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 
+0

首先感謝您的幫助!我想指定我最終使用的代碼(因爲我需要在具有ASH而不是BASH的BusyBux上運行腳本,並且<<<正在生成錯誤)是:__echo $ THR | awk -v chawk = $ pos -v thrawk = $ val -F',''{$ chawk = thrawk;打印}'OFS = \,__ – EnriqueH