我想弄清楚如何搜索和替換.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
這與失蹤報價有關。但是,您可以簡單地使用'sed -i「s/$ oldPass/$ newPass/g」users.txt'替換最後2行。 sed的'-i'標誌表示就地並將直接保存對文件的更改。 – Aserre