Deleting part of a string : string manipulation

i have something like this...

 echo "teCertificateId" | awk -F'Id' '{ print $1 }' |  awk -F'te' '{ print $2 }'
Certifica

the awk should remove 'te' only if it is present at the start of the string.. anywhere else it should ignore it.

expected output is

Certificate

Without external programs (fast)

var=teCertificateId
var2=${var#te}
var3=${var2%Id}
echo "$var3"

With external programs:

echo "$var" | sed 's/^te//;s/Id$//'
2 Likes

Hi

$  echo "teCertificateId" | awk -F'Id' '{sub(/^te/,"",$1); print $1 }'
Certificate

Guru,

1 Like

thanks a lot :slight_smile:

And a third way:

echo "teCertificateId"| sed 's/^te//; s/Id$//'
1 Like
 
echo "teCertificateId" | nawk '{gsub("^te|Id$","",$0);print}' 
Certificate

A neater way within ksh is to slice the variable and it doesn't spawn a new process. If you know that "te" is to be removed from the begginning and "Id" from the end then it's simply like Scrutinizer wrote:-

var="teCertificateId"
var2="${var#te}"
echo "${var2%Id}"

however if you just want to trim any two leawding and trailing characters you need to use the wildcard ?:-

var=teCertificateId
var2="{var##??}"
echo "{var2%%??}"

Does this help?

Robin
Liverpool/Blackburn
UK

@rbatte1: This form of parameter expansion should work with any POSIX compliant shell, not just ksh.

Since with ?? the number of positions is still fixed there is no difference between lazy and greedy matching so a single # and a single % would work too..