I am working on one shell script which search directory modified in last 24 hours and then compress them using tar.

Folder Search :

find /path to log directory/ -maxdepth 1 -type d -mtime +0 

example output:

/path to log directory/01_05_2016
/path to log directory/02_05_2016
/path to log directory/03_05_2016
/path to log directory/04_05_2016

Truncate unnecessary character:

find /path to log directory/ -maxdepth 1 -type d -mtime +0 | tr -d "_" | tr -d "path to log directory"

example output:

01052016 02052016 03052016 04052016

Separate the truncated strings as individual array element using "sed":

# Folder search

declare -a array="($(find <0-24 hour directory serach> | <truncate uncecessary character> | sed 's/\([0-9]*\).*/[\1]="\1"/'))"

# Array Printing
echo "Number of Array Elements: "${#array[@]}
echo "array[01052016]: " ${array[01052016]}
echo "array[02052016]: " ${array[02052016]}
echo "array[03052016]: " ${array[03052016]}
echo "array[04052016]: " ${array[04052016]}

example output

Number of Array Elements: 4
array[01052016]: 01052016
array[02052016]: 02052016
array[03052016]: 03052016
array[04052016]: 04052016

Compress the output:

LOG_DIR_NAME='<find folder>'

xargs tar -cvzPf /ouput folder/logname.tar.gz  /path to log directory $LOG_DIR_NAME

Problem Statment:

By the use of sed command, I can separate the search string into an individual array element. With the use of this command

sed 's/\([0-9]*\).*/[\1]="\1"/'

where [\1] defines my array index and "\1" defines my element.

Desired Output I am interested in getting the array element stored from index (0 to n)

array[0]: 01052016
array[1]: 02052016
array[2]: 03052016
array[3]: 04052016

How can I customize the array indexing in this case or traverse thru the array without knowing the start index?

Please help

Thank you


First of all, you should simplify your command to:

$ find "/path to log directory/" -maxdepth 1 -type d -mtime +0 | sed 's#.*/##; s#_##g' 

Next, to save as an array, you could just do:

array=( $(find "/path to log directory/" -maxdepth 1 -type d -mtime +0 | sed 's#.*/##; s#_##g') )

That saves it as you want, in an array with numerical, increasing indices starting from 0:

$ for i in {0..3}; do echo "$i : ${array[$i]}"; done
0 : 01052016
1 : 03052016
2 : 04052016
3 : 02052016

That said, if you do find yourself needing to iterate over an associative array, you can do that too:

$ declare -a array=( "foo"=>"bar" "baz"=>"bad" )
$ for i in ${!array[*]}; do echo "$i : ${array[$i]}"; done
baz : bad
foo : bar
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.