i have files like appklm220250408114500RequestKPI.dat.gz. The time is always 00 15 30…
- User
i have files like appklm2_20250408114500_Request_KPI.dat.gz. The time is always 00 15 30 and 45 i use below timestamp to get file name. But i need it to finish with 00 or 15 or 30 or 45. If the timestamp is 20250408115800 it needs to be 20250408114500 file_name_time=$(date +'%Y%m%d%H%M')
- Assistant
To modify your shell script to generate a timestamp that always rounds down to the nearest quarter-hour (00, 15, 30, or 45), you can use
dateand some arithmetic. Here's how you can do that:- Extract the current minutes from the timestamp.
- Determine the nearest previous quarter-hour based on the current minutes.
- Build the new timestamp.
Here's an example of how you can achieve this in a shell script:
#!/bin/bash # Get the current date and time. current_time=$(date +'%Y%m%d%H%M') # Extract the current minute. minute=$(echo "$current_time" | cut -c 12-13) # Calculate the nearest previous quarter-hour. if [ $minute -ge 45 ]; then rounded_minute=45 elif [ $minute -ge 30 ]; then rounded_minute=30 elif [ $minute -ge 15 ]; then rounded_minute=15 else rounded_minute=0 fi # Format the new time with the calculated minute. new_time=$(echo "$current_time" | sed "s/\(.*\)\(..\)$/\1$(printf '%02d' $rounded_minute)/") echo "$new_time" - User
current_time=$(date +'%Y%m%d%H%M') i need 3 hour ago
- Assistant
To get the time 3 hours ago in the same format while still rounding down to the nearest quarter-hour, you can modify the previous example. Instead of using the current time directly, you'll first calculate the time 3 hours ago using the
datecommand with the-doption. Here's how to do that:#!/bin/bash # Get the time 3 hours ago. time_three_hours_ago=$(date -d '3 hours ago' +'%Y%m%d%H%M') # Extract the current minute. minute=$(echo "$time_three_hours_ago" | cut -c 12-13) # Calculate the nearest previous quarter-hour. if [ $minute -ge 45 ]; then rounded_minute=45 elif [ $minute -ge 30 ]; then rounded_minute=30 elif [ $minute -ge 15 ]; then rounded_minute=15 else rounded_minute=0 fi # Format the new time with the calculated minute. new_time=$(echo "$time_three_hours_ago" | sed "s/\(.*\)\(..\)$/\1$(printf '%02d' $rounded_minute)/") echo "$new_time"