Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the number of the field

Tags:

bash

shell

unix

awk

i have this line in the file:

,2,353867835022;11,353681041426390,272023201187741,272-02f-20017-06609,353854100352;11,,,,,,,0854100352,3,00,,O,D,DATA,,,7124395,,,17687,16,HPLMN,M20MSS_TTFILE_8377_20110528170245,M20MSS,W30B22I;0GRI3,1,20110528130013,170054,1,41,,,,,,,,0,,,,,,,,,,,,,,,,,,353868001820,,,,b60a5c0014,1:353867835022::::0854100352::353854100352,,,,,,,,

Yes, this is a comma"," separated file.there is a number 17687 .I want to know what is the number of that field in the line. i want to use that as a base and include that in a shell script.

like image 569
Vijay Avatar asked Dec 28 '22 20:12

Vijay


2 Answers

Field #26:

% awk -F',' '/17687/ {
    for (f = 0; f < NF; ++f) {
        if ($f == "17687") {
            print $f " found in field number " f " of " NF " on line " NR "."
        }
    }
}' test.csv
17687 found in field number 26 of 75 on line 1.

This allows for finding 17687 in multiple fields on multiple lines.

Hope this helps.

like image 58
Johnsyweb Avatar answered Dec 31 '22 15:12

Johnsyweb


So, you want the number of commas before the 17687? One way to do it is:

sed -r 's/(^.*,)17687,.*$/\1/;s/[^,]//g'|wc -c

This grabs everything before the 17687, removes all the non-commas, and counts the number of characters.

Using this in a script, you might do something like:

FIELD_NO=`sed -r 's/(^.*,)17687,.*$/\1/;s/[^,]//g'|wc -c`
cut -d',' -f$FIELD_NO some_file
like image 30
David Claridge Avatar answered Dec 31 '22 14:12

David Claridge