Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the line number of a string in another string in Shell

Tags:

grep

shell

awk

Given

str="hij";
sourceStr="abc\nefg\nhij\nlmn\nhij";

I'd like to get the line number of the first occurrence of $str in $sourceStr, which should be 3.

I don't know how to do it. I have tried:

awk 'match($0, v) { print NR; exit }' v=$str <<<$sourceStr
grep -n $str <<< $sourceStr | grep -Eo '^[^:]+';
grep -n $str <<< $sourceStr | cut -f1 -d: | sort -ug
grep -n $str <<< $sourceStr | awk -F: '{ print $1 }' | sort -u

All output 1, not 3.

How can I get the line number of $str in $sourceStr?

Thanks!

like image 656
Martin Avatar asked Nov 28 '25 03:11

Martin


1 Answers

You may use this awk + printf in bash:

awk -v s="$str" '$0 == s {print NR; exit}' <(printf "%b\n" "$sourceStr")

3

Or even this awk without any bash support:

awk -v s="$str" -v source="$sourceStr" 'BEGIN {
split(source, a); for (i=1; i in a; ++i) if (a[i] == s) {print i; exit}}'

3

You may use this sed as well:

sed -n "/^$str$/{=;q;}" <(printf "%b\n" "$sourceStr")

3

Or this grep + cut:

printf "%b\n" "$sourceStr" | grep -nxF -m 1 "$str" | cut -d: -f1

3
like image 195
anubhava Avatar answered Dec 01 '25 00:12

anubhava