1

I am using Ubuntu 18.04 LTS and I wish to copy files from one folder to another and along with it also wish to store the filepath of each file that's being copied from folder1 to folder2 in a third file with space as a separator.
NOTE: Since cp command does not return any output so storing it in file won't work.

Any mix of commands or script is welcome which can be run through terminal.

Please do not suggest any additional software.

  • additional to what? To what 18.04's ubuntu-minimal and its dependencies include? – Stéphane Chazelas Feb 20 at 15:49
  • yes additional to the default – Ashwani Shukla Feb 20 at 15:52
1

A combination of find and cpio can be used to recursively copy all files and subfolders from folder1 to folder2. With tee in between you can write all file names (relative to folder1) into outputfile.

cd folder1 && find . -depth | tee outputfile | cpio -pdm folder2

The command cd folder1 is necessary because cpio wants to get file names relative to the source folder.

folder2 must be specified either absolute or relative to folder1.

To copy files only you could modify the find command:

... find . -type f -maxdepth 1 ...
2

With POSIX commands and assuming the names of the files and directories don't contain newline characters:

src=/some/dir
dst=/some/other/dir
file_list=/path/to/list.txt
(cd -P -- "$src" && find . |
  tee -- "$file_list" |
  pax -rwdpe -- "$dst")

The paths will be relative to the $src or $dst directories (which need to exist beforehand).

The GNU implementation of cp (as found on Ubuntu) has a -v option that makes it tell what it's doing.

LC_ALL=C cp -va -- "$src" "$dst" > "$file_list"

Will create a list.txt that contains something like:

'/some/dir' -> '/some/other/dir'
'/some/dir/file' -> '/some/other/dir/file'
[...]

Another option would be to use tar (not a standard command, but Ubuntu comes with GNU tar by default):

(cd -P -- "$src" && tar cf - .) |
  (cd -P -- "$dst" && tar xvf - > "$file_list")
  • why cd command ? – Ashwani Shukla Feb 20 at 15:31
  • line 6: pax: command not found – Ashwani Shukla Feb 20 at 15:35
  • @AshwaniShukla, If you did find "$src" | pax -rwdpe "$dst" without the cd, that would create some /some/other/dir/some/dir directory structure on the destination. – Stéphane Chazelas Feb 20 at 15:46
  • Yes, it's a shame that Ubuntu comes without pax (a POSIX-mandated command), and with tar (a very unportable command) by default. – Stéphane Chazelas Feb 20 at 15:47
  • but tar command is used to create compressed files as far as I know. Please add the explanation of the command too, it would be great. – Ashwani Shukla Feb 20 at 15:49

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.