Linux

ubuntu linux shell腳本更改文本文件中一行的列值

  • November 3, 2016

所有這些都是以防萬一的方式編寫的:

情況1:

echo "${name}:${identity}:${hp}:$now:"0"" >> info.txt      # write to info.txt

所以我會有這樣的東西:Tom:8:987654:commission:0 # i assign it to 0 first

案例2:

echo -n "Enter employee's name:"
read name

S=`grep $name info.txt`;    

   if test -z $S 
then
echo "No details with employee name  $name"
else
echo "$S" | cut -d: -f4 // display 4th column.
echo 
echo -n "Enter hourly wage: "; read wage;
echo -n "Enter hours worked this week: "; read hours;

pay=$hours-40*$wage;          

echo -n "To update next payroll : press Y else N to go main menu: "     

read option
case "$option" in 
[Yy]*)  echo "Payroll have been updated."
   echo grep $name | sed -i s/\:*$/$pay/n info.txt //error         
   ;;
[Nn]*) 
   echo "Press Enter to view the Main"     
esac
fi

我的文本文件如下所示:

Tom:8:987654:commission:0
Tommy:7:12379813:hourly:0
Fan:5:2132131:salaried:0

我正在嘗試將最後一列值替換為 $ pay ( not all columns only the specific name by the user ) Lets say the $ pay 是 10,$name 是 Tommy

這是預期的文本文件:

  Tom:8:987654:commission:0
   Tommy:7:12379813:hourly:10
   Fan:5:2132131:salaried:0

但我得到了這個錯誤:sed: -e expression #1, char 15: unknown option tos'`

我在 ubuntu 終端上做。

替換整行:

sed -e "/$name/s/[0-9]*$/$pay/" -i info.txt

引用自:https://unix.stackexchange.com/questions/320753