My main goal is to set up variables which are taken from a string which can be of various lengths. Each variable must contain 4 digits from the string (ie var_1 = digits 1-4, var_2 = digits 5-8 etc). By using the fold -w4 command I can get the string into blocks of 4.
For example:
string = 1234567898765432
fold -w4:
1234
5678
9876
5432
Rather than manually create the variables by copying the data, can anyone suggest how I can get Bash to automatically create variables for each block of 4 that is created?
I have searched Google and even tried ChatGPT. The suggestion given doesn't seem to work:
# Get the length of the input string
length=${#input_string}
# Loop through the string in steps of 4 characters
for (( i=0; i<$length; i+=4 )); do
# Extract 4 characters starting from position i
substring="${input_string:i:4}"
# Create a variable with the extracted substring
var_name="var_$((i/4 + 1))"
declare "$var_name=$substring"
done
# Print the created variables
echo "Created variables:"
declare -p | grep -E '^declare -\w+ var_[0-9]+='
All that happens is I get the "Created variables" written to the terminal.
The normal approach would be to create an array of the entries, easily doable with
mapfile(orreadarray- a synonym ofmapfile); in this case we'll also use process substitution to feed thefoldresults tomapfile, eg:The chatGPT answer is working it's just that the final line of the script (
declare -p | grep -E ...) needs some tweaking. Alternatives for the last line: