2

I am learning Linux commands.

When rename the file name with timing info, there are : marks automatically assigned. how can I change this : sign to _?

Below is a file name example. It was updated with timing info. how to name it by replacing : with _?

ee_Sun_Aug_11_22:20:27_GMT-8_2019.txt

Also, why below did not work?

$ cp /var/log/ee.txt ee_`date`.txt
cp: target `2019.txt' is not a directory

1 Answer 1

6

To loop over all files in the current directory that contain at least one : character in their name and ends with .txt, and to change the : characters to _, with the ksh93, zsh, bash, mksh shells (or recent versions of busybox sh), you may use

for name in ./*:*.txt; do
    newname=${name//:/_}
    mv -i "$name" "$newname"
done

or, shorter,

for name in ./*:*.txt; do
    mv -i "$name" "${name//:/_}"
done

The parameter substitution ${name//:/_} would change all : to _ anywhere in the value $name (a ksh93 operator also supported by the shells mentioned above).

The mv -i would rename the file, but would ask for confirmation if the new name is already taken.

The filename that you show as an example would be changed to ee_Sun_Aug_11_22_20_27_GMT-8_2019.txt.


Your command

cp /var/log/ee.txt ee_`date`.txt

does not work because date outputs a string with spaces in it. The spaces would have made cp think you wanted to copy several files into a directory. Hence the "is not a directory" error.

The following would have worked better:

cp /var/log/ee.txt "ee_$(date).txt"

It works better, not because I changed your backticks to $(...) but because I double-quoted the new name.

This would have created the file ee_Sun Aug 11 16:57:37 CEST 2019.txt (or something similar).

To get a neater looking filename, you may want to specify the output format for date a bit more precisely:

cp ee.txt "ee_$(date +"%F_%H-%M-%S").txt"

The format string %F_%H-%M-%S would be described in the strftime(3) manual on your system (man 3 strftime), or in the manual for the date command, and you would end up with a filename like ee_2019-08-11_16-59-55.txt. If your date doesn't support the %F directive, you can replace with %Y-%m-%d.

Alternatively,

cp ee.txt "$(date +"ee_%F_%H-%M-%S.txt")"

(letting the date command format do most of the work in creating the new filename)

1
  • Thank you very much for advice above. Now my commands work Commented Aug 13, 2019 at 2:06

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.