Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Input : a=ABCD~BCDA~BABD~CACD~CICD~DEFG
Searching String : BABD
Output: 2

As per the above input i have a string with delimiter '~'.

Here, I want to get the delimiter position according to any of the search string from the input string.

Could anyone please help me out from it.


In case of unknown delimiters, how could i manage? Is a code can check multiple delimiters at a single go?


What I have tried:

I have tried with the below code but not able to find the delimiter's position.

echo $a |awk -v s="BABD" '{print index($1,s)}' 

Output: 11 instead of 2
Posted
Updated 6-May-20 0:30am
v2
Comments
Peter_in_2780 6-May-20 2:47am    
Ugly, brute force approach: Get the "11" as you did, then count the delimiters in that much of the input string.
Mohibur Rashid 6-May-20 3:14am    
CPalini has given you the answer.
You can try perl too :) all (I do not know any exception) linux distribution comes with perl.
Member 13777735 6-May-20 5:33am    
Yes yes. Thank you for your suggestion.

1 solution

This
awk -F "~" 'BEGIN{RS=FS}/BABD/{print NR-1}' <<< 'ABCD~BCDA~BABD~CACD~CICD~DEFG'
works for me (see Awk Field number of matched pattern at Stack Overflow[^]).
 
Share this answer
 
Comments
Member 13777735 6-May-20 5:29am    
Thank You. It has worked for me.
Member 13777735 6-May-20 5:53am    
I have some other doubts.

Suppose, I have around 4 delimiters like - '~','|','^|' and '^' and i can not suspect which delimiter will come for a particular run then how could i resolve this issue.

I just wanted to know in this code how i will use multiple delimiters.
CPallini 6-May-20 6:48am    
You may use multiple delimiters in AWK. See, for instance
https://stackoverflow.com/questions/12204192/using-multiple-delimiters-in-awk
It is not clear whether you need or not them (that is: do you need multiple delimiters in a single run?).
Member 13777735 7-May-20 9:09am    
How i could handle multiple delimiters like <"~", "|", "^" and "^|"> in this code,

awk -F "~" 'BEGIN{RS=FS}/BABD/{print NR-1}' <<< 'ABCD~BCDA~BABD~CACD~CICD~DEFG'

As the code is using only one delimiter mentioned in it.
Member 13777735 7-May-20 9:16am    
I got my answer. Thank you all.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900