2

The first field is the username, the second is the password, and the last indicates the action (login/register)

File 1: User input

hello,world,register

File 2: Plain text database

admin,123
user,321
foo,bar

How can i compare the user input with the database to check if the username already exists?

I´ve tried the following code, but it´s not working:

if cut -d "," -f1 user_input | grep -wf user_input database; then
    echo "This username is already in use, try again!"
else
    echo "Successfully registered!"
fi

PS: i need a solution without awk,sed or find, just grep and cut

1
  • Is user_input a file, or is it supposed to be an environment variable, or is the input string being piped to the script? Commented Feb 4, 2018 at 16:32

3 Answers 3

3

grep + cut approach:

if grep -qwf <(cut -d, -f1 user_input) database; then 
    echo "This username is already in use, try again!"
else
    echo "Successfully registered!"
fi
4
  • 1
    Sorry I didn't see the -f Commented Feb 4, 2018 at 16:34
  • @user1404316, read documentation about -f option and read the 1st comment unix.stackexchange.com/questions/421837/… Commented Feb 4, 2018 at 16:42
  • @HenriqueHBR, you're welcome Commented Feb 4, 2018 at 16:43
  • But why use the -f option at all? Commented Feb 4, 2018 at 16:44
0

A solution that only uses bash built-in and grep.

while IFS=',' read -r username
do
    if grep -wq $username database
    then
        echo "This username is already in use, try again!"
    else
        echo "Successfully registered!"
    fi
done < user_input
0

I done by using cut command,for loop and if condition

#!/bin/bash
 i=`cut -d "," -f1 user_input.txt`

#echo $i
for j in `cut -d "," -f1 database.txt`
do
if [[ $i == $j ]]
then
echo $j "already exsists"
else
echo $j "doesn't exsists"
fi
done

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.