Split a non delimited file into columns depending on user input

I would like some advice on some code.

I want to write a small script that will take an input file of this format

111222233334444555666661112222AAAA
2222333445556612323244455445454545
2334556345643534505435345353453453

(and so on)

It will be called as : script inputfile X (where X is the number of slices you want to do)

I want the script to read the file and column-ize the slices, depending on user input, ie if he gave input 1,2 for the first slice, 3,4 for the second, the output would look like this:

111 1222
222 2333
233 3455

This is what i have so far, but i only get the outputs of the first slicing arranged in a line, any advice please?

#Initialize arrays
for ((i=1 ; i <= $2; i++)); do
        echo "Enter starting digit of $i string"; read a
        echo "Enter length in digits of $i string"; read b
done 

#Skim through file, slice strings

while read line
do
            for i in "${a[@]}"; do
            str=${line:${a}:${b}}
            done

            for i in "${str[@]}"; do
            echo -n "$i "
            done


done <$1

Assuming you're using a shell that recognizes arrays, the following seems to avoid your syntax and logic errors:

#Initialize arrays
for ((i=1 ; i <= $2; i++))
do	echo "Enter starting digit of $i string"; read a
	echo "Enter length in digits of $i string"; read b
done 

#Skim through file, slice strings
while read line
do	for ((i=1; i < $2; i++))
	do	printf '%s ' "${line:${a}:${b}}"
	done
	printf '%s\n' "${line:${a[$2]}:${b[$2]}}"
done <$1

Note that the output you showed would come from the input 1,3 and 3,4; not 1,2 and 3,4.

1 Like

You wanted to enter the substring coordinates in the n,m format. Try this small adaption of Don Cragun's suggestion:

for ((i=1 ; i <= $2; i++))
  do    echo "Enter starting digit and length of $i string"; IFS="," read a[$i] b[$i] REST
  done 
      
while read line
  do    for ((i=1; i < $2; i++))
          do    printf '%s ' "${line:${a[$i]}:${b[$i]}}"
          done
        printf '%s\n' "${line:${a[$2]}:${b[$2]}}"
  done <$1

@Don Cragun: there seems to be missing the $ sign preceding the i loop variable?

1 Like

In the standards, a variable name (but, obviously, not a positional parameter) in expression in:

$((expression))

can be presented with or without a leading <dollar-sign> character to get the value to which the variable expands. At least in bash and in ksh , the same is true in the expression in

${array_name[expression]}
2 Likes

Both suggestions were really helpful! I m new to this forum so if there's a way to upvote your help just clue me in! Ty!!

I'm glad that we were able to help you solve your problem.

If you find that a post helped you, hitting the :b:Thanks button at the bottom left corner of that post signifies your appreciation to the person who submitted that post.

1 Like