LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   find one field into another (https://www.linuxquestions.org/questions/linux-newbie-8/find-one-field-into-another-4175413927/)

lcvs 06-28-2012 08:19 PM

find one field into another
 
Hi guys !

Using awk, I try to read a column and see if a string from a field in this column is present into a longer string from another field in the same column.
If it is the case, returns the sub-string length (RLENGTH) in a new field.
input:
Code:

111|abcd1234efgh|zzzzz
222|1234|yyyyyyyyyy
333|ij1234k|xxx
444|ui987654g|ww

I tried using match function:
Code:

awk 'BEGIN{FS=OFS="|"} {match(a[$2],$2); print $4 = RLENGTH}1' input
to obtain:
Code:

111|abcd1234efgh|zzzzz|8
222|1234|yyyyyyyyyy|4
333|ij1234k|xxx|5
444|ui987654g|ww|-1


But I don't manage to write a for loop to scan the entire column by taking every field one by one as a reference for match function. It returns $4 = "-1" for every record.

chrism01 06-28-2012 08:35 PM

I reckon you can extend this one liner to match first, then sort by length http://unstableme.blogspot.com.au/20...g-awk-and.html & only print last record

lcvs 06-28-2012 08:45 PM

Hi Chrism01, thanks for your help !

The problem is that it doesn't tell me if it found the shorter string within another field ($4 = -1 for all records).

lcvs 06-28-2012 09:24 PM

edited first post

schneidz 06-30-2012 06:50 PM

not sure what you are trying to do (shouldnt your 3rd row = 6 ?).

anyways, this is my stab at it:
Code:

[schneidz@hyper ~]$ cat lcvs.txt
111|abcd1234efgh|zzzzz
222|1234|yyyyyyyyyy
333|ij1234k|xxx
444|ui987654g|ww
[schneidz@hyper ~]$ awk 'BEGIN{FS=OFS="|"}  {print  index($2,"1234")}' lcvs.txt
5
1
3
0



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