0

我有一个文本文件(particulars.txt),其中包含

personId,personName,employmentType

详情.txt

1,jane,partTime
2,bob,fullTime
3,john,fullTime

如何做到这一点,如果我输入工人的姓名,它将检查该人是全职还是兼职工人,并提示用户输入薪水并仅为该人重写回文件. 我将更详细地解释。

例如

Enter Name:jane 
jane is a partTime staff
Enter Hourly Salary:10

所以文本文件(particulars.txt)现在将是

1,jane,partTime,10
2,bob,fullTime
3,johnfullTime

示例二

Enter Name:bob
bob is a fullTime staff
Enter monthly Salary:1600

所以文本文件(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 来实现我的结果感到困惑,从而寻求你们的帮助。提前致谢

4

2 回答 2

2

除非您需要以交互方式进行操作,否则您可以说:

sed '/\bbob\b/{s/$/,1600/}' filename

这将添加,1600到行匹配bob。请注意,通过指定单词边界\b,您可以确保仅针对bob而不是abobor进行更改boba

您可以使用该-i选项对文件进行就地更改:

sed -i '/\bbob\b/{s/$/,1600/}' filename

编辑:为了使用 shell 变量,对sed命令使用双引号:

 sed "/\b$employeeName\b/{s/^$/,$monthlySalary/}" filename
于 2013-10-28T05:51:05.057 回答
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
于 2013-10-28T05:55:56.457 回答