Jamuna Nandeesh
Jamuna Nandeesh

Reputation: 1

Split a single string into two or three variables in UNIX

I have a SESSION_TOKEN which gets generated dynamically every 30 mins. Its character length is greater than 530 and approximately 536 characters will be there in it.

How can i split this string in UNIX scripting. Need help.

Upvotes: 0

Views: 84

Answers (2)

Bill Karwin
Bill Karwin

Reputation: 562348

Bash variable expansion has substring operations built in:

$ string="abcdefghijklmnopqrstuvwxyz";
$ first=${string:0:8}
$ second=${string:8:8}
$ third=${string:16}

$ echo $first, $second, $third
abcdefgh, ijklmnop, qrstuvwxyz

Upvotes: 1

BradHards
BradHards

Reputation: 702

You can use the "cut" utility for this kind of fixed length work:

echo "AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHHIIIIJJJJKKK" | cut -c 10-20
CCCDDDDEEEE

The -c means "select by character" and the "10-20" says which characters to select.

You can also select by byte (using -b) which might make a difference if your data has some unusual encoding.

In your case, where you want to do multiple chunks of the same string, something like:

bradh@saxicola:~$ export somethingToChop="AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHHIIIIJJJJKKK"
bradh@saxicola:~$ echo $somethingToChop | cut -c 1-10
AAAABBBBCC
bradh@saxicola:~$ echo $somethingToChop | cut -c 11-20
CCDDDDEEEE
bradh@saxicola:~$ echo $somethingToChop | cut -c 20-
EFFFFGGGGHHHHIIIIJJJJKKK

Would probably be the easiest to understand.

Upvotes: 1

Related Questions