Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to retrieve first 5 characters (only number & alphabet) from string in bash

Tags:

bash

shell

I have a string like that

1-a-bc-dxyz

I'd want to get 1-a-bc-d ( first 5 characters, only number and alphabet)

Thanks

like image 486
zuki Avatar asked Mar 08 '23 11:03

zuki


1 Answers

With gawk:

   awk '{ for ( i=1;i<=length($0);i++) { if ( match(substr($0,i,1),/[[:alnum:]]/)) { cnt++;if ( cnt==5) { print substr($0,1,i) } } } }' <<< "1-a-bc-dxyz"

Read each character one by one and then if there is a pattern match for an alpha-numeric character (using the match function), increment a variable cnt. When cnt gets to 5, print the string we have seen so far (using the substr function)

Output:

 1-a-bc-d
like image 175
Raman Sailopal Avatar answered May 15 '23 04:05

Raman Sailopal