Emma
Emma

Reputation: 470

Bash index of first character not given

So basically something like expr index '0123 some string' '012345789' but reversed.
I want to find the index of the first character that is not one of the given characters...
I'd rather not use RegEx, if it is possible...

Upvotes: 0

Views: 208

Answers (4)

user2350426
user2350426

Reputation:

Even if shell globing might look similar, it is not a regex.

It could be done in two steps: cut the string, count characters (length).

#!/bin/dash
a="$1"                  ### string to process
b='0-9'                 ### range of characters not desired.
c=${a%%[!$b]*}          ### cut the string at the first (not) "$b".
echo "${#c}"            ### Print the value of the position index (from 0).

It is written to work on many shells (including bash, of course).

Use as:

$ script.sh "0123_some string"
4
$ script.sh "012s3_some string"
3

Upvotes: 0

anubhava
anubhava

Reputation: 785781

Using gnu awk and FPAT you can do this:

str="0123 some string"

awk -v FPAT='[012345789]+' '{print length($1)}' <<< "$str"
4

awk -v FPAT='[02345789]+' '{print length($1)}' <<< "$str"
1

awk -v FPAT='[01345789]+' '{print length($1)}' <<< "$str"
2

awk -v FPAT='[0123 ]+' '{print length($1)}' <<< "$str"
5

Upvotes: 1

Andreas Louv
Andreas Louv

Reputation: 47117

I know this is in Perl but I got to say that I like it:

$ perl -pe '$i++while s/^\d//;$_=$i' <<< '0123 some string'
4

In case of 1-based index you can use $. which is initialized at 1 when dealing with single lines:

$ perl -pe '$.++while s/^\d//;$_=$.' <<< '0123 some string'
5

I'm using \d because I assume that you by mistake left out the number 6 from the list 012345789

Index is currently pointing to the space:

0123 some string
    ^ this space

Upvotes: 0

karakfa
karakfa

Reputation: 67547

You can remove chars with tr and pick the first from what is left

left=$(tr -d "012345789" <<< "0123_some string"); echo ${left:0:1}
_

once you have the char to find the index follow the same

expr index "0123_some string" ${left:0:1}
5

Upvotes: 1

Related Questions