I'd to Prefix my files (.dat) like this :

CLY_BIZ_COM_PERD.dat -> 20160622CLY_BIZ_COM_PERD.dat

I have tried the following:

key=`date "+%Y%m%d"`
for i in $(ls /Path/*.dat); do mv ${i} "${key}${i}" ;done

But this command suffix my files and not prefix it. How can I do this?

  • Does it, really? Try it again (add an echo before the mv to echo what would have happened without actually doing it).
    – Kusalananda
    Jun 22 '16 at 16:14
  • The result is : CLY_BIZ_COM_PERD.dat20160622 and not 20160622CLY_BIZ_COM_PERD.dat i need the second result Jun 22 '16 at 16:18
  • 2
    I doubt the loop works very well at all, as it would try to prefix the date to "/Path" instead of to the *.dat filenames themselves
    – Jeff Schaller
    Jun 22 '16 at 16:22
  • 1
    Change $(ls /Path/*.dat) to /Path/*.dat
    – coffeMug
    Jun 22 '16 at 16:23
  • if you have rename command (written in Perl), first change to target directory and try rename "s/(.*)/$(date +%Y%m%d)\1/" *.dat
    – Sundeep
    Jun 22 '16 at 16:23

Two changes to your current script:

  1. don't parse ls; instead rely on the shell's globbing

  2. because the files are in a subdirectory, either cd there first and run the loop, or use basename and dirname to pull out the directory and filename portions of the file before adding the prefix.

(Note: I also changed your "/Path" to "./Path" as I didn't want to create a root-level /Path directory. Same principles apply, though.

To set up some sample files:

mkdir Path && cd Path
touch CLY_BIZ_COM_PERD.dat jeff.dat a.dat c\ d.dat
cd ..

Here's a dry run:

for f in ./Path/*.dat
  printf "mv '%s' '%s'\n" "$f" "$(dirname "$f")/${key}$(basename "$f")"

Output of the dry run:

mv './Path/a.dat' './Path/20160622a.dat'
mv './Path/c d.dat' './Path/20160622c d.dat'
mv './Path/CLY_BIZ_COM_PERD.dat' './Path/20160622CLY_BIZ_COM_PERD.dat'
mv './Path/jeff.dat' './Path/20160622jeff.dat'

Once you're content, do it for real:

for f in ./Path/*.dat
  mv "$f" "$(dirname "$f")/${key}$(basename "$f")"

... and the result:

$ ls -1 Path
20160622c d.dat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.