Devolviendo una columna con grep

I'm attempting to search through a file and return a particular column based on whether a particular value is present in the column. For example, if I search for "Red" in the file:

One    Two    Three
Cat    Dog    Chicken
Blue   Black  Red
Blah   Blah   Blah

I want returned:


I would even accept just knowing which column grep or any other search command found a match in, so I could use cut, but I can't even find that much.

preguntado el 09 de septiembre de 13 a las 23:09

You could try using color option, which can highlight the particular word, which can I help identify column. grep "string" --color -

What if the string you're looking for appeared in multiple columns - do you want all matching columns printed or the first one o something else? Do you want an RE match so Re.* cerillas Red y Refer or a strict string comparison? Do you want to match on partial words so Red coincidiría Reds or Redder? -

Sorry for the late reply, but I'm trying to find all columns that have a complete match. -

2 Respuestas

Esta es una forma:

Store all the data in the matrix a[line][column]. Save the column number in p. Finally print all the items a[line][p].

$ awk -v text=Blue '{for (i=1; i<=NF; i++) {a[NR,i]=$i; if ($i~text) {p=i}}} END{ for (i=1; i<=NR; i++) print a[i,p]}' a
$ awk -v text=Red '{for (i=1; i<=NF; i++) {a[NR,i]=$i; if ($i~text) {p=i}}} END{ for (i=1; i<=NR; i++) print a[i,p]}' a


To have exact matches, replace ~ con == (thanks konsolebox):

awk -v text=Blue '{for (i=1; i<=NF; i++) {a[NR,i]=$i; if ($i==text) {p=i}}} END{ for (i=1; i<=NR; i++) print a[i,p]}' a

contestado el 23 de mayo de 17 a las 13:05

+1 for the clean solution. == can be used too instead of ~ to have exact matches even with regex characters. - konsolebox

One possibility, depending on how you respond to the questions I posted in my comment:

awk -v tgt="Red" '
  NR==FNR {for (i=1;i<=NF;i++) if ($i==tgt) cols[i]; next}
  {sep=""; for (i=1;i<=NF;i++) if (i in cols) {printf "%s%s", sep, $i; sep=OFS}; print ""}
' file file

Respondido el 10 de Septiembre de 13 a las 01:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.