Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickest way to split a string in bash

Tags:

string

bash

sed

The goal: produce a path from an integer. I need to split strings in fixed length (2 characters in this case), and then glue the pieces with a separator. Example : 123456 => 12/34/56, 12345 => 12/34/5.

I found a solution with sed:

sed 's/\(..\)/\1\//g'

but I'm not sure it's really quick, since I'm really not searching for any analysis of the string content (which will always be an integer, if it's any importance), but really to split it in length 2 (or 1 if the original length is odd).

like image 701
MarvinLeRouge Avatar asked Apr 24 '26 04:04

MarvinLeRouge


1 Answers

bash expansion can do substring

var=123456
echo "${var:0:2}"  # 2 first char
echo "${var:2:2}"  # next two
echo "${var:4:2}"  # etc.

joinning manually with /

echo "${var:0:2}/${var:2:2}/${var:4:2}"
like image 199
Nahuel Fouilleul Avatar answered Apr 25 '26 18:04

Nahuel Fouilleul