12345678 = 123 45 67 8 in bash
I have a script that takes in one big 17 digit number开发者_开发知识库 as input from the command line. I want to separate it into 5 different numbers, each with different no. of digits. Like so:
Input: 23063080434560228
Output of the program:
Number1: 23063
Number2: 08
Number3: 04
Number4: 3456
Number5: 0228
Now the output of the program (in terms of digits per number) is fixed, i.e, Number2
will always have 2 digits and so on. Given this sort of a scheme of the output, I am not sure if division is even an option. Is there some bash
command/utility that I can use? I have looked it over the net and not come across much.
Thanks,
Sriram.You can use Substring Extraction:
${string:position:length}
Extracts length
characters of substring from string
starting at position
.
For example:
INPUT=23063080434560228
num1=${INPUT:0:5}
num2=${INPUT:5:2}
num3=${INPUT:7:2}
num4=${INPUT:9:4}
num5=${INPUT:13:4}
You can put this directly into an array in one shot in Bash 3.2 or greater.
string=23063080434560228
pattern='(.{5})(.{2})(.{2})(.{4})(.{4})'
[[ $string =~ $pattern ]] && substrings=(${BASH_REMATCH[@]:1})
for substring in "${substrings[@]}"; do echo "$substring"; done
精彩评论