Devolviendo una columna con grep
Frecuentes
Visto 758 veces
0
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:
Three
Chicken
Red
Blah
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.
2 Respuestas
3
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
One
Cat
Blue
Blah
$ 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
Three
Chicken
Red
Blah
Noticias
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
0
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 search awk grep cut or haz tu propia pregunta.
You could try using color option, which can highlight the particular word, which can I help identify column. grep "string" --color - SKPS
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.*
cerillasRed
yRefer
or a strict string comparison? Do you want to match on partial words soRed
coincidiríaReds
orRedder
? - Ed MortonSorry for the late reply, but I'm trying to find all columns that have a complete match. - user2762945