Reputation: 883
I would like some advice on some code.
I want to write a small script that will take an input file of this format
$cat filename.txt
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:
#Here the first slice starts on the second digit, and length = 2 digits
#Here the second slice starts on the 3th digit and legth=4 digits
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?
$./columncut filename.txt 2
#Initialize arrays
for ((i=1 ; i <= $2; i++)); do
echo "Enter starting digit of $i string"; read a[i]
echo "Enter length in digits of $i string"; read b[i]
done
#Skim through file, slice strings
while read line
do
for i in "${!a[@]}"; do
str[i]=${line:${a[i]}:${b[i]}}
done
for i in "${!str[@]}"; do
echo -n "$i "
done
done <$1
I am unaware if there's an easier to do a job like this, perhaps with awk? Any help would be much appreciated.
Upvotes: 1
Views: 658
Reputation: 641
#usage: bash slice.sh d.txt "1-2" "4-8" "10-20"
#column postions 1-2, 4-8 and 10-20 printed.
#Note that it is not length but col position.
inf=$1 # source file
shift # arg1 is used up for file discard it.
while read -r line
do
for fmt #iterate over the arguments
do
slice=`echo $line | cut -c $fmt` # generate one slice
echo -n "$slice " # oupt with two blanks, but no newline
done
echo "" # Now give the newline
done < "$inf"
Sample run:
bash slice.sh d.txt "1-2" "4-8" "10-15"
11 22223 334444
22 23334 555661
23 45563 564353
Probably it is not very difficult to store all these generated slices in array.
Upvotes: 2