我想弄清楚如何搜索和替换.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