2016-12-05 87 views
0

我想弄清楚如何搜索和替换.txt文件中特定行和特定列上的密码。这是什么样子:bash:搜索并替换.txt文件中的密码

Admin1 Pass1 1 
Admin2 Pass2 1 
User1 Upass1 0 
User2 Upass2 0 

这里是我的代码:

while (true) 
do 
read -p 'Whose password would you like to change? Enter the corresponding user name.' readUser 
userCheck=$(grep $readUser users.txt) 

if [ "$userCheck" ] 
then 
    echo $userCheck > temp2.txt 

    read -p 'Enter the old password' oldPass 
     passCheck=$(awk '{print$2}' temp2.txt) 

    if [ "$passCheck" == "$oldPass" ] 
    then 

     read -p 'Enter the new password' newPass     
     sed -i "/^$readUser/ s/$oldPass/$newPass/" users.txt 
     break 
    else 
     echo 'The username and/or password do not match. Please try again.' 
    fi 
else 
    echo 'The username and/or password do not match. Please try again.' 
fi 
done 

假设用户1的密码被与测试所取代,这就是结果:

Admin1 Pass1 1 Admin2 Pass2 1 User1 TESTING 0 User2 Upass2 0 

我需要的是:

Admin1 Pass1 1 
Admin2 Pass2 1 
User1 TESTING 0 
User2 Upass2 0 
+0

这与失踪报价有关。但是,您可以简单地使用'sed -i“s/$ oldPass/$ newPass/g”users.txt'替换最后2行。 sed的'-i'标志表示就地并将直接保存对文件的更改。 – Aserre

回答

1

你原来的脚本几乎可以工作,只缺少正确的引用。你可以写下:echo "$updatePass" > data用双引号保留换行符。有关报价的更多信息here

但是,您的脚本还有改进的空间。你可以这样写:

#!/bin/bash 

while (true) 
do 
    read -p 'Whose password would you like to change?' readUser 

    # no need for a temporary variable here 
    if [ "$(awk -v a="$readUser" '$1==a{print $1}' users.txt)" ] 
    then 
     read -p 'Enter the old password' oldPass 
     # the awk code checks if the $oldPass matches the recorded password 
     if [ "$oldPass" == "$(awk -v a="$readUser" '$1==a{print $2}' users.txt)" ] 
     then 
      read -p 'Enter the new password' newPass 
      # the -i flag for sed allows in-place substitution 
      # we look for the line begining by $readUser, in case several users have the same password 
      sed -i "/^$readUser/ s/$oldPass/$newPass/" users.txt 
      break 
     else 
      echo 'The username and/or password do not match. Please try again.' 
     fi 
    else 
     echo 'The username and/or password do not match. Please try again.' 
    fi 
done 
+0

我试着实现上述解决方案,但我仍然得到相同的不需要的输出。任何想法为什么会发生这种情况? –

+0

然后,这必须与您的代码的另一部分相关。到目前为止,我只是应付了这个代码并将其粘贴到shell脚本中,并将其用于您的示例输入。 – Aserre

+0

我发布了修改后的代码。使用改进的代码提供了与仅将代码更改为使用sed -i相同的结果,因此我现在已决定使用该代码。 –