• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 512
  • Last Modified:

String Split based on position

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

#!/bin/bash
SPLIT_NUM="5"
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?

ALEx604


0
ALEx604
Asked:
ALEx604
1 Solution
 
yuzhCommented:
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}-`
else
    echo "Position outside the string length!"
fi

0
 
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

ALEx604
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now