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

strstr() alternative for bash

I need to search a string for a substring, if the substring is found print the string upto the end of the substring.i.e

str="this is a long string"
substring="long"
expected="this is a long"

I have tried bash string manipulation and failed. Tried to use an awk command, but I can’t get it right.
This works if substring is not in a variable, but I require it in a variable since the input varies.

awk -F'long' '{print $1}' <<<$str

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

awk -v myvar="$substring"  -F'myvar' '{print $1}' <<<$str

prints the whole string.
Any help will be appreciated.

>Solution :

If you looked for bash only solution, one of the options would be:

sfx="${str#*${substring}}"
expected="${str%"${sfx}"}"

Which uses prefix removal (of anything + $substring) to determine the trailing part. And then uses suffix removal to trim that from $str yielding your expected value.

Since you seem to be OK with answers beyond just shell (like using awk), here’s similar with sed:

echo "$str" | sed -e 's#^\(.*'"${substring}"'\).*#\1#'

-> match the whole line with anything up to and including $substring being saved in the first group and replace that line with content of the first matched group.

note: both of these examples are not greedy and will match up to the first $substring.

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