我试图找出如何搜索和替换.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
假设正在用TESTING替换User1的密码,结果就是:
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 :(得分: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