Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find 2 exact strings in same line in a file in bash

I have a file called details.txt in bash like below .

1#abc#123#xyz#2024-12-09#2
1#abc#123#xyz_123#2024-12-09#2
1#abc#123#bbc#2024-12-09#2

I am trying to find the line in which a 2 exact strings are present in the same line.

For example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if the input strings I am passing are abc and xyz then I want the first line as my output

1#abc#123#xyz#2024-12-09#2

But I am getting below as output

1#abc#123#xyz#2024-12-09#2
1#abc#123#xyz_123#2024-12-09#2

But when I pass abc and xyz_123 then I am getting the correct result.

Below is the code snippet of what I have done

wf_name='abc'
session_name='xyz'

# grep session details from batch_details.txt
sess_details=$(grep $wf_name.*$session_name details.txt)

what am I doing wrong here. what is the correct code.

>Solution :

Check this out:

$ grep "${wf_name}\b.*${session_name}\b" file
1#abc#123#xyz#2024-12-09#2

\b is meant for word boundaries


With awk:

$ awk -F'#' -v wf_name=$wf_name -v session_name=$session_name '$2==wf_name && $4==session_name' file
1#abc#123#xyz#2024-12-09#2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading