I am writing a Script in which one of the functions is to search in a text file DNI or Name that the user is asked for and when they are found, print the entire lines.
The file has the format "DNI | Name"
2:Pepe
21:Julio
1:Marta
The function buscarNombre
works correctly for me:
function buscarNombre()
{
echo Introduce Nombre a buscar:
read nombrex
nombrex=`grep "\$nombre\b" agenda.txt`
echo $nombrex
menu
}
But the searchDNI function, instead of searching and printing a specific DNI, searches for me and prints any DNI that contains the number that I have passed to them.
function buscarDNI()
{
echo Introduce DNIx a buscar:
read DNIx
DNIx=`grep "\$DNIx\b" agenda.txt`
echo $DNIx
menu
}
If, for example, I tell it to look for the DNI:2, it will print the lines 2:Pepe and 21:Julito and I only want it to print 2:Pepe.
How can I improve buscarDNI
so that it only searches for the exact DNI?
Use
grep -w
, which searches for the exact wordI can't reproduce your error. That said, you should probably create a more complex condition to check the data. For example:
To see the DNI, validate that it is at the beginning of the line and follow the character ":":
To see the name, check that it is after the ":" and followed by the end of the line:
However, with Awk all this is much easier: you have a file with fields separated by ":". So with Awk finding the row whose 2nd column is exactly "Pepe" is as easy as saying:
And the same with the 1st column:
In this way, you will be finding exactly what you are looking for, without having to resort to regular expressions or twisting Grep to filter it well.
So your function would be something like: