Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting beginning alphabets of a string in bash/ash

Tags:

sed

awk

cut

ash

How can I extract the beginning alphabetic letters from a string? I want to extract alphabets occurring in the beginning before I hit the first non-alphabetic character.

e.g. If the input string is abcd045tj56 the output should be abcd

Similarly, if the input is jkl657890 the output should be jkl

Can it be done in shell script using awk/sed/cut?

I tried

echo "XYZ123" | awk 'sub(/[[:alpha:]]*/, "")'

But it gives 123 instead of xyz

Then I tried

echo "XYZ123" | awk '{print (/[[:alpha:]]*/)}'

but it gives 1

I want the answer to be XYZ

like image 630
Deepali Joshi Avatar asked Oct 29 '25 02:10

Deepali Joshi


2 Answers

Converting my comment to an answer here. Using any awk version.

awk '
match($0,/^[a-zA-Z]+/){
  print substr($0,RSTART,RLENGTH)
}
' Input_file

OR:

awk '
match($0, /[^[:alpha:]]/){
  print substr($0, 1, RSTART-1)
}
' Input_file
like image 180
RavinderSingh13 Avatar answered Nov 01 '25 09:11

RavinderSingh13


You may use this sed:

sed 's/[^[:alpha:]].*$//'

This sed matches a non-alpha character and everything afterwards and substitutes with an empty string.

Examples:

sed 's/[^[:alpha:]].*$//' <<< 'abcd045tj56'
abcd

sed 's/[^[:alpha:]].*$//' <<< 'XYZ123'
XYZ

sed 's/[^[:alpha:]].*$//' <<< 'jkl657890'
jkl

If you want to do this in bash then:

s='abcd045tj56'
echo "${s/[^[:alpha:]]*}"

abcd
like image 32
anubhava Avatar answered Nov 01 '25 09:11

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!