LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Find a field number for a value in text value - BASH (https://www.linuxquestions.org/questions/programming-9/find-a-field-number-for-a-value-in-text-value-bash-518003/)

severian23 01-10-2007 09:01 AM

Find a field number for a value in text file - BASH
 
I'm trying to find a bash solution to return the field number for a string in a tab-delimited text file. Anyone have an idea?

MensaWater 01-10-2007 09:41 AM

awk -Ft would parse a line using tabs as delimiters.

You could do something like:

Code:

FLDCNT=1
for FIELD in `cat <file> |awk -Ft '{print $0}' inputline`
do if echo $FIELD |grep <pattern> >/dev/null 2>&1
  then echo <pattern> was found in field $FLDCNT
  fi
  FLDCNT=`expr $FLDCNT + 1`
done


Of course you'd put in whatever word/pattern you're looking for in palce of <pattern> and your text file name in place of <file>.

Note this gives you the field number per line so if you had it on more than one line you could see multiple field numbers (one for each line it is found on).

colucix 01-10-2007 09:45 AM

With gawk you can try

Code:

gawk '{split($0,array,"\t"); for (x in array) if (array[x] == "string") {print x}}' filename.txt
this look for a field that matches exactly the given "string". If you look for a field that contains a given "substring", you can try

Code:

gawk '{split($0,array,"\t"); for (x in array) if (match(array[x],"substring") > 0) {print x}}' filename.txt

severian23 01-10-2007 09:49 AM

[QUOTE=colucix]With gawk you can try

Code:

gawk '{split($0,array,"\t"); for (x in array) if (array[x] == "string") {print x}}' filename.txt
this look for a field that matches exactly the given "string".

___________________

Thanks so very much! That was exactly what I needed. I appreciate all your help!


All times are GMT -5. The time now is 08:20 AM.