Finding first 6 characters

Hi ,
I'm using KSH88

I tried the following example to get the last 6 characters from a string

 echo 'abcdefghids' | sed 's/.*\(.\{6\}\)$/\1/'

What chages i need to do to get the first 6 characters from the string
my desired output should be abcdef

Thank you

A simple cut would be

echo 'abcdefghids' | cut -c -6
1 Like

Hello,

Could you please try to use the folliwng to get the last 6 characters as per your request.

 
awk '{print substr($0,(length($0)-6))}' FILE Name

 

Please let me know in case you have any queries.

Thanks,
R. Singh

1 Like

parameter expansion

 
var=abcdefghids
echo ${var:$((-6))}
1 Like

Hey,

Try sth like this,

If your grep supports -o option, It will give you first 6 characters of the string.

echo 'abcdefghij'|grep -o '^.\{6\}'

Cheers!!
-R

To smile689,

vidyadhar85 has the best solution as it does not spawn another process. If you have a lot of data to process, spawning a process each time can be very time consuming. If you shell doesn't quite like his syntax (or you want something similar, but in just ksh) you can use this slightly messier one:-

var=abcdefghis
newvar="${var%${var##??????}}"
echo $newvar

Robin
Liverpool/Blackburn
UK

Unfortunately ${var:offset} is not available in ksh88

Good solution, if you add double quotes the subsitution gets protected from possible special characters in the replacement string :

var=abcdefghis
printf "%s\n" "${var%"${var##??????}"}"

--
(still thanks for that, @alister)

1 Like