Bash scripting does my head in. I have searched for regex assignment, but not really finding answers I understand.
I have files in a directory. I need to loop through the files and check if they fit certain criteria. File names under a certain sequence need to have their sequence increased. Those over a certain sequence need to trigger an alert.
I have pseudo code and need help turning it into correct bash syntax:
#!/bin/sh
function check_file()
{
# example file name "LOG_20101031144515_001.csv"
filename=$1
# attempt to get the sequence (ex. 001) part of file
# if sequence is greater than 003, then raise alert
# else change file name to next sequence (ex. LOG_20101031144515_002.csv)
}
for i in `ls -Ar`; do check_file $i; done;
If PHP were an option, I could do the following:
function check_file($file){
//example file 'LOG_20101031144515_001.csv';
$parts = explode('.',$file);
preg_match('/\d{3}$/', $parts[0], $matches);
if ($matches){
$sequence = $matches[0];
$seq = intval($sequence);
if ($seq > 3){
// do some code to fire alert (ex. email webmaster)
}
else{
// rename file with new sequence
$new_seq = sprintf('%03d', ++$seq);
$new_file = str_replace("_$sequence", "_$new_seq", $file);
rename($file, $new_file);
}
}
}
So long story short, I'm hoping someone can help port the PHP check_file function to the bash equivalent.
Thank you