Find an exact name in a text file with Bash

1

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 he finds them he will print the whole lines.

The file has the format "DNI | Name"

  2:Pepe
 21:Julio
  1:Marta

The buscarNombre function works correctly for me:

function buscarNombre()
{

    echo Introduce Nombre a buscar:
    read nombrex

    nombrex='grep "\$nombre\b" agenda.txt'
    echo $nombrex
    menu
}

But the function look for DNI instead of looking for and printing a DNI in particular I look for and print any DNI that contains the number that I have passed them.

function buscarDNI()
{

    echo Introduce DNIx a buscar:
    read DNIx

    DNIx='grep "\$DNIx\b" agenda.txt'
    echo $DNIx
    menu
}

If for example, I tell him to look for the DNI: 2, he will print lines 2: Pepe and 21: Julito and I just want you to print 2: Pepe.

How can I improve buscarDNI to only search for the exact ID?

    
asked by RandomName 10.04.2018 в 21:48
source

2 answers

1

Use grep -w , which searches for the exact word

function buscarDNI()
{

    echo Introduce DNIx a buscar:
    read DNIx

    DNIx='grep -w "\$DNIx\b" agenda.txt'
    echo $DNIx
    menu
}
    
answered by 10.04.2018 / 22:38
source
0

I can not reproduce your error. That said, you should probably create a more complex condition to review the data. For example:

To see the DNI, validate that it is at the beginning of the line and the character ":" follows:

grep "^$dni:" agenda.txt

To see the name, validate that it is after ":" and followed by the end of the line:

grep ":$nombre$" agenda.txt

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:

awk -F: '$2=="Pepe"' fichero

And the same with the 1st column:

awk -F: '$1==2' fichero

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:

function buscarDNI ()
{
    echo "Introduce DNI a buscar:"
    read dni
    awk -F: -v valor_dni="$dni" '$1==valor_dni' fichero
    menu
}
    
answered by 10.04.2018 в 22:42