LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   comparing 2 strings in shell script (https://www.linuxquestions.org/questions/programming-9/comparing-2-strings-in-shell-script-573870/)

dhanabalanb 08-01-2007 02:07 AM

comparing 2 strings in shell script
 
Hi,

My file has entries as follows:

root:x:678:79789:home
welcome:x:698:79489:temp
welcometomyhome:x:698:79489:tmp

And I have a sting welcome stored in a variable called variable. I want to check for the string stored in variable through shell scipt. It should only give me welcome from my file. It should not give welcometomyhome (but this also has welcome in it). Can anyone please help me in this regard?

Thank you,
Dhanabalan.

ljbuturovic 08-01-2007 03:03 AM

Assuming your text file is named `welcome.txt',
create a script named welcome.sh:

#!/bin/sh
variable="welcome"
export string=$variable
awk -F: '$1 == ENVIRON["string"]' welcome.txt

After making the script executable:

$ ./welcome.sh
welcome:x:698:79489:temp

Ljubomir

gjagadish 08-01-2007 05:58 AM

The below code will print the exact line you wanted

------------------------------
#!/bin/bash
variable="welcome"
grep "^$variable\:" welcome.txt
--------------------------------

makyo 08-01-2007 01:17 PM

Hi.

Some versions of grep have a "word" search option, "-w":
Code:

#!/bin/sh

# @(#) s1      Demonstrate word-search in grep.

set -o nounset
echo
echo "GNU bash $BASH_VERSION" >&2
grep --version | head -1 >&2
echo

variable="welcome"

cat >data1 <<EOF
root:x:678:79789:home
welcometomyhome:x:698:79489:tmp
welcome:x:698:79489:temp
EOF

grep -w "$variable" data1

exit 0

producing:
Code:

% ./s1

GNU bash 2.05b.0(1)-release
grep (GNU grep) 2.5.1

welcome:x:698:79489:t

See man grep for details ... cheers, makyo


All times are GMT -5. The time now is 07:34 AM.