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.

2
  • additional to what? To what 18.04's ubuntu-minimal and its dependencies include? Commented Feb 20, 2019 at 15:49
  • yes additional to the default Commented Feb 20, 2019 at 15:52

2 Answers 2

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") 
7
  • why cd command ? Commented Feb 20, 2019 at 15:31
  • line 6: pax: command not found Commented Feb 20, 2019 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. Commented Feb 20, 2019 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. Commented Feb 20, 2019 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. Commented Feb 20, 2019 at 15:49
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 ... 
1
  • why cd command ? Commented Feb 20, 2019 at 15:31

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.