2016-12-05 49 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相同的結果,因此我現在已決定使用該代碼。 –