0

Here's the output of a grep command I ran:

[user@localhost] : ~/Documents/challenge $ grep -i -e ".\{32\}" fileA fileB
fileA:W0mMhUcRRnG8dcghE4qvk3JA9lGt8nDl
fileB:observacion = new Observacion();
fileB:observacion.setCodigoOf(ordenBO.getCodigo());
fileB:observacion.setDetalle(of.getObservacion().getSolicitante());
fileB:observacion.setTipoObservacion(TipoObservacionOrdenFleteMaestro.SOLICITANTE);
fileB:observacion.setProceso(TipoProcesoObservacionMaestro.MODIFICACION);
fileB:observacion.setFecha(Utiles.getFechaSistema());
fileB:java.util.Date fechaHora = Calendar.getInstance().getTime();
fileB:observacion.setUsuarioCrecion(usuarioSesionado.getUsuario().getUsuario());
fileB:daoObservacion.agregaObservacion(observacion);

I'm looking for 32 character long string in two files: fileA and fileB. Importantly, fileA contains exactly 32 characters only, with no line breaks:

[user@localhost] : ~/Documents/challenge $ hexdump -C fileA
00000000  57 30 6d 4d 68 55 63 52  52 6e 47 38 64 63 67 68  |W0mMhUcRRnG8dcgh|
00000010  45 34 71 76 6b 33 4a 41  39 6c 47 74 38 6e 44 6c  |E4qvk3JA9lGt8nDl|
00000020

The problem with my grep command is that it is returning any line that has more than 32 chars. How can I make it return only lines with exactly 32 chars. The issue for me is that I can't modify my regex to match on a line break, because there is no line break.

My expected output would be simply:

fileA:W0mMhUcRRnG8dcghE4qvk3JA9lGt8nDl

(note: this is for a challenge that I've already solved with my ugly solution, but in this scenario we can only use grep and piping or redirecting output is not allowed)

5

This works. ^ denotes start of line, plus the {32} you already had, then a $ for end of line.

$ cat fileA fileB
12345678901234567890123456789012
123456789012345678901234567890123
12345678901234567890123456789012
123456789012345678901234567890124
$ grep -E "^.{32}$" fileA fileB
fileA:12345678901234567890123456789012
fileB:12345678901234567890123456789012
$

And as pointed out by @steeldriver, posix grep includes -x, so the following approach also works : grep -xE ".{32}" fileA fileB

  • 2
    POSIX grep should also support the -x or --line-regexp whole-line match, I think – steeldriver Jul 14 '15 at 19:11
1

According to the GNU Grep documentation:

If the final byte of an input file is not a newline, grep silently supplies one.

So, if you're using GNU grep, you should be able to use the beginning-of-line/end-of-line anchors (^ and $) as usual, even if you're not working on properly-formed plaintext files.

grep '^.\{32\}$' fileA fileB

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.