我有一个包含
的文本文件(particulars.txt)PERSONID,PERSONNAME,employmentType
particulars.txt
1,jane,partTime
2,bob,fullTime
3,john,fullTime
如何操作,如果我输入工作人员的名字,它将检查该人是全职或兼职工作人员并提示用户输入工资并重写回文件对那个人。我会详细解释。
例如
Enter Name:jane
jane is a partTime staff
Enter Hourly Salary:10
所以textfile(particulars.txt)现在将是
1,jane,partTime,10
2,bob,fullTime
3,johnfullTime
示例二
Enter Name:bob
bob is a fullTime staff
Enter monthly Salary:1600
所以textfile(particulars.txt)现在将是
1,jane,partTime,10
2,bob,fullTime,1600
3,john,fullTime
这就是我所拥有的 我的代码
#!/bin/bash
fileName="particulars.txt"
read -p "Enter name:" name
if grep -q $name $fileName; then
employmentType=$(grep $name $fileName | cut -d, -f4)
echo "$name is $employmentType" staff"
if [ $employmentType == "partTime" ]; then
echo "Enter hourly pay:"
read hourlyPay
#calculations for monthly salary(which I have not done)
elif [ $employmentType == "fullTime" ]; then
echo "Enter monthly salary:"
read monthlySalary
fi
else
echo "No record found"
fi
read -p "Press[Enter Key] to Contiune.." readEnterKey
我只能找到这个人所属的雇佣类型,但我不知道如何/我应该怎样做才能在该行的最后为该特定的人添加薪水。我已经阅读了sed,但我仍然对如何使用sed来实现我的结果并因此寻求你们的帮助感到困惑。提前致谢
答案 0 :(得分:2)
除非您需要以交互方式进行,否则您可以说:
sed '/\bbob\b/{s/$/,1600/}' filename
这会将,1600
添加到与bob
匹配的行中。请注意,通过指定字词边界\b
,您可以确保仅对bob
而非abob
或boba
进行更改。
您可以使用-i
选项对文件进行就地的更改:
sed -i '/\bbob\b/{s/$/,1600/}' filename
编辑:为了使用shell变量,请对sed
命令使用双引号:
sed "/\b$employeeName\b/{s/^$/,$monthlySalary/}" filename
答案 1 :(得分:1)
我刚修改了你的剧本。
#!/bin/bash
fileName="particulars.txt"
read -p "Enter name:" name
if grep -q $name $fileName; then
employmentType=$(grep $name $fileName | cut -d, -f3)
emp_name=$(grep $name $fileName | cut -d, -f2) # Getting emp name
emp_id=$(grep $name $fileName | cut -d, -f1) # Getting id
echo "$name is $employmentType staff"
if [ $employmentType == "partTime" ]; then
echo "Enter hourly pay:"
read hourlyPay
#calculations for monthly salary(which I have not done)
sed -i "s/^$emp_id.*$/&,$hourlyPay/g" $fileName # Modifying the file by using id.
elif [ $employmentType == "fullTime" ]; then
echo "Enter monthly salary:"
read monthlySalary
fi
else
echo "No record found"
fi
read -p "Press[Enter Key] to Contiune.." readEnterKey
我添加了以下几行。
emp_id=$(grep $name $fileName | cut -d, -f1)
emp_name=$(grep $name $fileName | cut -d, -f2)
sed -i "s/^$emp_id.*$/&,$hourlyPay/g" $fileName