String Split based on position

Using bash scripting (#!/bin/bash GNU)

VAR="8gbwirbfvrw8ovhnrogv4" ; # no spaces or new lines folks, could be any alphanumeric string
# ?
echo $RESULT

Split the string at position 5 ($SPLIT_NUM)
so the output of echo $RESULT should be "8gbwi"
unless we change SPLIT_NUM="10" so then the output would be "8gbwirbfvr"
or whatever the string is.

My thoughts on # ? section:

I could echo out $VAR to a new file and split with (no pun intended) "split" but that's not really splitting a variable, it's splitting a file.

I was thinking that since sed allows you to use "." for characters, and ^ for first posistion you could just delete the rest of the string, which is fine by me, but I am not knowledgable enough to get this fine tuned enough if $SPLIT_NUM changes.

I know it can be done in perl, but I need this in a bash script, so maybe awk it? Or does grep allow you to get the first x number of characters in a string and ignore the rest?


Who is Participating?
You can do:

PART1=`echo $VAR | cut -c1-${SPLIT_NUM}`
PART2=`echo $VAR | cut -c${SPLIT_NUM}-`

You need to check the string length, before doing the split, eg

if [ ${SPLIT_NUM} -le ${#VAR} ] ; then
    PART1=`echo $VAR | cut -c1-${SPLIT_NUM}`
    PART2=`echo $VAR | cut -c${SPLIT_NUM}-`
    echo "Position outside the string length!"

ALEx604Author Commented:
# ?
RESULT=`perl chars = split(//, $VAR) | for NEXT in $chars ; do if [ $SPLIT_NUM > 0 ] then echo $NEXT ; fi ; done`

needs tweeking, just another idea

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.