Operating System - Linux
1832350 Members
2636 Online
110041 Solutions
New Discussion

cut the last few character(s) in a word

 
Sajeesh O.K
Advisor

cut the last few character(s) in a word

Hi

Anybody know how to cut last few character(s)
from a word.

I have sclap1,scl_ap2,sclk_ap3...sclok_ap20. and want to cut 1,2...20. or atleast ap1,ap2,....ap20

Thanks
Sajeesh
3 REPLIES 3
Slawomir Gora
Honored Contributor

Re: cut the last few character(s) in a word

Hi,

you can use tr utility:
ex:
echo sclk_ap3 | tr -d [:digit:]
Hein van den Heuvel
Honored Contributor

Re: cut the last few character(s) in a word


Is the input all on one line?
Always comma seperated?

If you just want those numbers, then you could delete anything else using tr -d.
For example:

$ cat x
clap1,scl_ap2,sclk_ap3,...sclok_ap20
$ cat x | tr -d "_a-z"
1,2,3,...20

Same thing using perl, where you can use samrter regexpr as needed (not used here):

$perl -pe 's/[_a-z]*//g' x

Often I find i need a bit more logic and would prefer to deal with each line and each 'word'. In perl that could look like:

$ perl -ne 'foreach $word(split /,/)
{ $word =~ s/^(\D*)//; print "$word\n"}' x
1
2
3
20


The -ne is an implied loop over the input lines reading into $_

The foreach loops through the result of a split on the default $_ assigning to $word

The block first performs a subsitute on $word, then prints.

Hein.








Muthukumar_5
Honored Contributor

Re: cut the last few character(s) in a word

You can try like,

# cat file
sclap1
scl_ap2
sclk_ap3
sclok_ap20
# sed 's/^.*\([a-z][a-z].*\)/\1/' file
ap1
ap2
ap3
ap20

-Muthu
Easy to suggest when don't know about the problem!