2

I want to copy and rename multiple files from one directory to another. Particularly, I want something like this:

/tmp/tmp.XXX/aaa.original.txt
/tmp/tmp.XXX/bb5.original.txt
/tmp/tmp.XXX/x2x.original.txt

copied into

/root/hello/dump-aaa.txt
/root/hello/dump-bb5.txt
/root/hello/dump-x2x.txt

I've tried some things like these which don't work:

  • cp /tmp/tmp.XXX/*.original.txt /root/hello/*.txt
  • find /tmp/tmp.XXX/ -name '*.original.txt' | xargs -i cp /root/hello/dump-{}.txt
  • for f in /tmp/tmp.XXX/*.original.txt; do cp -- "$f" "/root/hello/dump-$f.txt"; done

Usually the above codes result in error:

cp: cannot create regular file '/root/hello/dump-/tmp/tmp.XXX/aaa.original.txt.txt': No such file or directory

1

bash solution:

for f in /tmp/tmp.XXX/*.original.txt; do 
    bn="${f##*/}"   # extracting file basename
    cp "$f" "/root/hello/dump-${bn%%.*}.txt"
done

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.