2) Write a bash script named q2. sh that can be used to “timestamp” files by ren
ID: 3571643 • Letter: 2
Question
2) Write a bash script named q2.sh that can be used to “timestamp” files by renaming them.
The script should expect some arguments, which should be file names. If no arguments are given, the script should print a short help message about script usage and exit.
Example:
if (( $# != 1 )); then
-------------------------------------------
If some arguments are provided, the script should check that they are regular files and rename them to indicate the current time. For any argument that is not a regular file, a warning message should be printed. I
f an argument is a regular file, for example, file.txt it should be renamed according to the following rules:
Let us say that the script is run on Nov 3, 2016, at 2:34pm. The script should try to rename the example file to 2016-11-03-file.txt. However, if such file already exists, then the script should rename the file to 2016-11-03-1434-file.txt.
If this file exists as well, then the script should keep looking for a file name such as:
2016-11-03-1434-1-file.txt
2016-11-03-1434-2-file.txt
2016-11-03-1434-3-file.txt
...
until a name is found such that such file does not exist. If the count reaches 1000, then the script should give up on renaming the file, report an error, and continue with the next argument.
-----------------------------------------------------------------------------------------------
Code may help to write the program:
renameFile()
{
logfile="$MY_DIR/logs/sample.txt"
mv "$logfile" "$logfile.$(date +%H%M%S)"
if [ -f "$logfile" ]
then
for ((i=1;i<=100;i++));
do
mv "$logfile" "$logfile.$(date +%H%M%S)-1434-$i-file"
done
fi
}
Explanation / Answer
#!/bin/bash
#method to rename file and message and return true(0) or false(1)
renFile(){
file=$1
newfile=$2
if [ ! -f "$newfile" ]
then
echo "Renamed $file to $newfile!"
mv "$file" "$newfile"
return 0
else
return 1
fi
}
#method to scan and rename file return 0 true / 1 false
renameFile() {
file="$1"
#date prefix test and rename
dt=$(date +%Y-%m-%d)
newfile=$dt-$file
if renFile $file $newfile
then
return 0
fi
#time prefix test and rename
ts=$(date +%H%M)
newfile=$dt-$ts-$file
if renFile $file $newfile
then
return 0
fi
#time and iteration prefix test and rename
for i in {1..1000}
do
newfile=$dt-$ts-$i-$file
if renFile $file $newfile
then
return 0
fi
done
return 1
}
#main method
#check parameters
if (( $# != 1 )); then
echo usage: $0 filename
exit 1
fi
filen=$1
#check and rename file
if renameFile $filen
then
echo "rename successful"
else
echo "rename failed"
exit 1
fi
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.