Append The Time Stamp to a File Name in Ubuntu

Adding timestamp to a filename with mv in BASH

The few lines you posted from your script look okay to me. It's probably something a bit deeper.

You need to find which line is giving you this error. Add set -xv to the top of your script. This will print out the line number and the command that's being executed to STDERR. This will help you identify where in your script you're getting this particular error.

BTW, do you have a shebang at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had #! /bin/bash on top, but your bash interpreter is located in /usr/bin/bash, you'll see this error.

EDIT

New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?

Two ways:

  1. Select the Edit->EOL Conversion->Unix Format menu item when you edit a file. Once it has the correct line endings, Notepad++ will keep them.
  2. To make sure all new files have the correct line endings, go to the Settings->Preferences menu item, and pull up the Preferences dialog box. Select the New Document/Default Directory tab. Under New Document and Format, select the Unix radio button. Click the Close button.

Command to assign timestamp to the name of a file

If you are using Bash (/bin/bash), this will put the name of the file into the variable file_name:

$ printf -v file_name 'db_%(%m%d%Y%H%M)T.sql' -2
$ echo "File name is: '$file_name'"
File name is: 'db_022420212146.sql'

You can do this at any time in your script since -2 is a special value representing the time Bash started, i.e. when your script was run.

If you are using a POSIX shell (/bin/sh), then you must add this at the beginning of your script:

file_name=$(date +db_%m%d%Y%H%M.sql)

(of course this would work with Bash too)

Append date to a filename in linux

Something like can do the work:

a=somefile.txt
bname="${a%.*}"
ename="${a##*.}"
date=$(date +%d%m%Y%H%M%S)
echo ${bname}_${date}.${ename}

Append TimeStamp to a File Name

You can use DateTime.ToString Method (String)

DateTime.Now.ToString("yyyyMMddHHmmssfff")

or string.Format

string.Format("{0:yyyy-MM-dd_HH-mm-ss-fff}", DateTime.Now);

or Interpolated Strings

$"{DateTime.Now:yyyy-MM-dd_HH-mm-ss-fff}"

There are following custom format specifiers y (year), M (month), d
(day), h (hour 12), H (hour 24), m (minute), s (second), f (second
fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or
A.M) and z (time zone).

With Extension Method

Usage:

string result = "myfile.txt".AppendTimeStamp();
//myfile20130604234625642.txt

Extension method

public static class MyExtensions
{
public static string AppendTimeStamp(this string fileName)
{
return string.Concat(
Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString("yyyyMMddHHmmssfff"),
Path.GetExtension(fileName)
);
}
}

Bash alias create file with current timestamp in filename

Use single quotes to prevent immediate expansion.

alias unix='echo $(date +%s)'

Update: While I'm happy to have been able to explain the different expansion behavior between single and double quotes, please also see the other answer, by Robby Cornelissen, for a more efficient way to get the same result. The echo is unnecessary here since it only outputs what date already would output by itself. Therefore, date doesn't need to be run in a subshell.

Appending creation date on filename

You could use the following bash command:

find . -type f -exec bash -c 'mv "$1" "$(dirname "$1")/$(stat -c %w "$1" | sed "s/\([^.]*\).*/\1/;s/[-: ]/_/g")_$(basename "$1")"' _ {} \;

find looks for all regular file and rename using mv each file found.

The filename is built such that it gets the creation time appended at the beginning of the file.

In order to get the file creation time, I use stat with option -c %w instead of date -r that gives the modification time.

The sed command replaces the output from stat to the wanted format (with _).

How can I move a file and append a timestamp to its name via cron job?

First, I'd try and figure out the command on its own, without a cron job. What you're doing is something like this (with shortened directory paths for readability):

mv /foo/CBD_DATA.zip /foo/archives > /foo/archives/CBD_DATA_`date +%d%m%y`.zip

This moves the file and then creates a new empty file; there is no output from the mv command, and the redirection has nothing to redirect, so the file with the datestamp is empty.

The second argument for the mv command is the new location itself; if it is a directory, the filename stays the same, but if it is not a directory, it is interpreted as the new name. You don't need any redirection.

mv /foo/CBD_DATA.zip "/foo/archives/CBD_DATA_$(date '+%d%m%y').zip"

I have replaced the deprecated backticks in the command substitution with $(...) and quoted the expansion. Side note: if you can choose the datestamp format, I'd strongly recommend using +%F (or %Y%m%d) instead so it sorts chronologically.

With your paths and escaped for a cron job (do you really want to run this every minute?):

* * * * * mv /home/cbd_dev/CBD_DATA.zip "/home/sundaram_srivastava/archives/CBD_DATA_$(date +\%d\%m\%y).zip"

Bash: Rename file name to unix timestamp of modification date

find . -type f -exec \
sh -c '
for i do
d=$(dirname "$i")
[ "$d" = / ] && d=
n=${i##*/}
echo mv "$i" "$d/u-$(stat -c %Y "$i") $n"
done' _ {} +
  • This operates recursively in the current directory (.). It only targets regular files (not directories etc). Modify -type f and other flags if needed.

  • It just prints the mv commands, so you can review them. Remove the echo to run for real.

  • We use find to list the target files, and its -exec flag to pass this list to a shell loop where we can parse and modify the filenames, including stat to get the modification time.

  • I don't know your use case, but a better solution may be to just save the output of: find . -type f -printf '%p u-%T@\n' in a file, for later reference (this prints the file path and modification time on the same line). Also, maybe a snapshot (if possible).



Related Topics



Leave a reply



Submit