I am running into a weird issue with associative arrays in bash.
I have the following files in a directory:
ls -lart
drwxr-xr-x. 3 root root 4096 Feb 9 11:14 ..
-rw-r--r-- 1 root root 3275 Feb 9 14:16 1.txt
-rw-r--r-- 1 root root 3275 Feb 9 14:16 2.txt
-rw-r--r-- 1 root root 3275 Feb 9 14:16 3.txt
-rw-r--r-- 1 root root 0 Feb 12 15:19 a.txt
-rw-r--r-- 1 root root 0 Feb 12 15:19 123.txt
drwxr-xr-x 2 root root 4096 Feb 12 15:19 .The files are listed from the oldest to the newest.
-Sent the output of ls -lart to a file with the following command:
ls -lart --block-size=K /test |grep txt |awk '{print $9,$5}' > /tmp/filestodel.txtfilestodel.txt has the list of files (with associated size) with from the oldest to the newest:
cat /tmp/filestodel.txt 1.txt 4K 2.txt 4K 3.txt 4K a.txt 0K 123.txt 0Kwhere the first column has the name of the file and the second the size (in Kbytes)
-I define an array and push these entries into it:
declare -A cleanup
while read line do filetodelname=$(echo $line | awk {'print$1'}); filetodelsize=$(echo $line | awk {'print$2'}); cleanup[$filetodelname]=$filetodelsize done < /tmp/filestodel.txtthe idea is to delete files listed in th array from the oldest (first) to the newest, which would translate in starting to delete file 1.txt as per ls -lart output above.
The issue is that when I loop through the keys:
for K in "${!cleanup[@]}"; do echo $K; done #print filenamesI get this output:
2.txt
3.txt
123.txt
1.txt
a.txtwhich is clearly messed up!
How I can keep the original order of files in the array?
Thanks, dom
1 Answer
You'd need 2 arrays, index them by a number in the first pass: first will receive names, second - sizes; then index them by a number (from 0 to number_of_files - 1) again in the second pass, when doing the deletions.
2