Linux copy all file names

Copy all files in a directory to a local subdirectory in linux

I’d like to make a copy of all the existing files and directories located in this directory in new_subdir . How can I accomplish this via the linux terminal?

3 Answers 3

This is an old question, but none of the answers seem to work (they cause the destination folder to be copied recursively into itself), so I figured I’d offer up some working examples:

Copy via find -exec:

find . ! -regex ‘.*/new_subdir’ ! -regex ‘.’ -exec cp -r ‘<>‘ new_subdir \;

This code uses regex to find all files and directories (in the current directory) which are not new_subdir and copies them into new_subdir. The ! -regex ‘.’ bit is in there to keep the current directory itself from being included. Using find is the most powerful technique I know, but it’s long-winded and a bit confusing at times.

Copy with extglob:

cp -r !(new_subdir) new_subdir

If you have extglob enabled for your bash terminal (which is probably the case), then you can use ! to copy all things in the current directory which are not new_subdir into new_subdir.

Copy without extglob:

mv * new_subdir ; cp -r new_subdir/* .

If you don’t have extglob and find doesn’t appeal to you and you really want to do something hacky, you can move all of the files into the subdirectory, then recursively copy them back to the original directory. Unlike cp which copies the destination folder into itself, mv just throws an error when it tries to move the destination folder inside of itself. (But it successfully moves every other file and folder.)

Источник

How to copy and add prefix to file names in one step?

I often add the -v option to cp to allow me to watch the progress.

You can use shell globbing:

for f in *.c; do cp -- "$f" "$OTHERDIR/old#$f"; done 

The for variable in GLOB format will expand the glob to all matching files/directories (excluding hidden-ones) and iterate over them, saving each in turn as $variable (in the example above, $f ). So, the command I show will iterate over all non-hidden files, copying them and adding the prefix.

If I do for f in /foo/bar/*.c , $f will contain the entire path, instead only the name of the file. How can I obtain only the name of the file?

@alexandernst either cd /foo/bar/; for f in *c , or use for f in /foo/bar/*.c; do name=$ . or name=$(basename «$f») .

Here is a one-liner using xargs , tr and globbing. Might have some value.

echo *.c | tr ' ' '\n' | xargs -n1 -I<> cp "<>" "PREFIX<>" 

This returns all files matching *.c as a space-separated string. Next, tr turns the extra spaces into newlines (N.B. did not test file names with spaces**). Then, xargs gets populated with each file name, and runs cp with the appropriate name and prefix.

Читайте также:  Форматировать флешку через консоль линукс

*.c can be modified for other, useful globs. Other prefixes in the xargs and cp part can be used as well.

**for those with spaces in their filenames:

(requires find that supports -print0 ) Similar to above, we can use find to output a null-seperated list of files, and tweak xargs with a flag to separate on null

find . -name '*.c' -print0 | xargs -0 -n1 -I<> cp "<>" "PREFIX<>" 

Источник

How to Copy Files in Linux

File copying is one of the most common tasks for PC users. Of course, you can use a file manager, navigate to a directory with your file, and copy files using a graphical interface. It is pretty simple. But in this article I will show how to copy files in the Linux terminal.

The graphical interface may be not available due to system crashes on home PCs. Although serves do not have it at all. In addition, copying files in the terminal is more flexible and powerful. In this article, I will not only cover the most popular cp command but also other commands such as tar, rsync, and find.

How to Copy Files in Linux

1. cp

The cp command is the most commonly used command for copying files in Unix-like operating systems. It is available out of the box in all distributions and has a lot of features. You can read in detail about this command in the article Command cp in Linux. In this article, I will provide multiple basic examples of using this utility.

Copying files into another folder is the simplest case. For example, use the following command to copy a picture from the home directory into a directory named pictures:

cp-sl-pic-png-sl-pictures-sl.png

Additionally, you can specify the name explicitly:

cp ~/pic.png ~/pictures/wallpaper.png

cp-sl-pic-png-sl-pictures-sl-wallpaper-png.png

If you want to copy one directory into another, use the -r option:

cp-r-sl-reports-sl-documents.png

In this case, the reports directory will be copied into the documents folder. If you want to copy the contents of the reports folder into ~/documents, use the -T option:

cp-rt-sl-reports-sl-documents.png

This command also supports special wildcard symbols * and ?. For example, the following command will copy all files whose names start with april:

cp ~/reports/april* ~/documents

cp-sl-reports-sl-april-sl-documents.png

If you want to preserve permissions mode and ownership, use the -p option:

cp -p ~/reports/march* ~/documents/

cp-p-sl-reports-sl-march-sl-documents-sl.png

Finally, there is an interesting use case for creating backups of files. You can Bash brace expansion syntax to make your command shorter, for example:

sudo-cp-sl-etc-sl-passwd-bask.png

This command will create a file with the same name and the .back extension.

By default, cp does not print the progress bar for file copying. It can be inconvenient when you are copying large files. However, you can use the progress command to show the progress for all commands from the CoreUtils package. Alternatively, you can use the rsync command instead of cp.

2. rsync

This command was designed to create backups for files and directories. It allows not only to copy files, but also synchronize the content of directories, and it supports transferring files through a network, for example, SSH.

To copy a picture into the ~/pictures directory use this command:

rsync-sl-pic-png-sl-pictures-sl.png

Here you can specify the file name as well as when you use cp. But this utility is more convenient because it can print information about the copying process. You can enable it using the —progress option:

Читайте также:  Настройка пользователей linux сервер

rsync —progress ~/disk.img ~/images

rsync-progress-sl-disk-img-sl-images.png

If you want to copy the contents of one directory into another, use the -r option. For example:

rsync -r ~/reports/ ~/documents/

rsync-r-sl-reports-sl-sl-documents-sl.png

Note, that if you want to copy only the content of the source directory, its name should end with a slash. But if you want to copy the directory itself, just don’t add the slash:

rsync -r ~/reports ~/documents/

rsync-r-sl-reports-sl-documents-sl.png

If you want to preserve permission mode and ownership, use the -a option:

rsync -a ~/reports ~/documents/

rsync-a-sl-reports-sl-documents-sl.png

3. xcp

Currently, there are several alternatives to the CoreUtils utilities that are written in Rust. These alternatives are optimized for modern systems and are more user-friendly. One such alternative is the xcp command, which is an alternative to the cp command. To install xcp, use cargo:

cargo install xcp

The xcp command can copy a file from one directory to another just like the cp command, but it also features a progress bar. For example:

xcp-sl-pic-png-sl-pictures-sl.png

You can also specify a new name for the file:

xcp ~/pic.png ~/pictures/wallpaper.png

xcp-sl-pic-png-sl-pictures-sl-wallpaper-png.png

Copying directories is also straightforward. All contents of the source directory are copied into the destination directory by default:

xcp-r-sl-reports-sl-documents-sl.png

But if you want to copy the ~/reports directory into ~/documents itself, use the -T option:

xcp-rt-sl-reports-sl-documents-sl.png

Now, you know basic commands that can help to copy files in Linux. Let’s have a look at filtering files for copying.

Copying Files in Linux Using Regular Expression

Sometimes, you may want to filter files for copying by regular expression. You can use the find command to do this. It allows to apply different conditions and regular expressions for searching files and then run a specific command for each file, such as cp, rsync and even xcp.

For example, use this command to copy all files whose names contain the march word and numbers from the ~/reports directory into documents:

find ./reports -regex ‘./[^/]*/march9*’ -exec cp <> ~/documents ;

find-sl-reports-regex-sl-sl-sl-marc.png

The regex parameter is used to specify a regular expression for filtering files. Note, that the regular expression is applied to a whole file path. The exec parameter specifies a command which should be executed for each file. The <> is a placeholder that will be replaced with the name of each file that matches the regular expression, and the ; is used to terminate the -exec option. You can use other find conditions in the same way.

Special Copying of Files Using Tar Command

Linux provides multiple ways to perform the same task, and that’s what makes it interesting for many users. Copying files in Linux can be done not only by using cp or other copying tools. For instance, you can use the cat utility and Bash output redirection operators to copy the contents of a file to another file:

cat report > ~/reports/report

This command copies only the content of the file. It can be useful for small text files.

If you want to copy multiple files you can use the tar command. For example, if you want to create a system backup while preserving all permissions, ownership, and symbolic links, you can use tar with Bash pipeline where tar will archive the required files and send the result to stdout, and another tar instance will extract the files into the specified folder. Here’s an example command:

Читайте также:  Long int size in linux

tar cf — /var | ( cd /mnt/var && tar xvf — )

This command will copy all contents from /var into /mnt/var. You can use it to copy Linux folders or a whole root of a system. The cp command can also be used for this purpose, but you need to specify the -a option to preserve permissions and links.

Wrapping Up

Now, you know how to copy files in Linux. As you can see, copying in the terminal is more flexible, and sometimes faster than in a GUI if you remember the proper commands. If you have any questions, feel free to leave them in the comments below!

Found a mistake in the text? Let me know about that. Highlight the text with the mistake and press Ctrl+Enter.

Источник

copy a directory structure with file names without content

I have a huge directory structure of movie files. For analysis of that structure I want to copy the entire directory structure, i.e. folders and files however I don’t want to copy all the movie files while I want to keep there file names. Ideally I get zero-byte files with the original movie file name. I tried to and then rsync to my remote machine which didn’t fetch the link files. Any ideas how to do that w/o writing scripts?

4 Answers 4

find src/ -type d -exec mkdir -p dest/<> \; \ -o -type f -exec touch dest/<> \; 

Find directory ( -d ) under ( src/ ) and create ( mkdir -p ) them under dest/ or ( -o ) find files ( -f ) and touch them under dest/ .

You can user mv creatively to resolve this issue.

Other (partial) solution can be achieved with rsync:

rsync -a --filter="-! */" sorce_dir/ target_dir/ 

The trick here is the —filter=RULE option that excludes ( — ) everything that is not ( ! ) a directory ( */ )

It doesn’t copy file data. From manpage of cp

--attributes-only don't copy the file data, just the attributes 

Note: I’m not sure this option available for other distributions, if anybody can confirm please update the answer.

I needed an alternative to this to sync only the file structure:

rsync --recursive --times --delete --omit-dir-times --itemize-changes "$src_path/" "$dst_path" 

This is how I realized it:

# sync source to destination while IFS= read -r -d '' src_file; do dst_file="$dst_path$" # new files if [[ ! -e "$dst_file" ]]; then if [[ -d "$src_file" ]]; then mkdir -p "$dst_file" elif [[ -f $src_file ]]; then touch -r "$src_file" "$dst_file" else echo "Error: $src_file is not a dir or file" fi echo -n "+ " ls -ld "$src_file" # modification time changed (files only) elif [[ -f $dst_file ]] && [[ $(date -r "$src_file") != $(date -r "$dst_file") ]]; then touch -r "$src_file" "$dst_file" echo -n "+ " ls -ld "$src_file" fi done < <(find "$src_path" -print0) # delete files in destination if they disappeared in source while IFS= read -r -d '' dst_file; do src_file="$src_path$" # file disappeard on source if [[ ! -e "$src_file" ]]; then delinfo=$(ls -ld "$dst_file") if [[ -d "$dst_file" ]] && rmdir "$dst_file" 2>/dev/null; then echo -n "- $delinfo" elif [[ -f $dst_file ]] && rm "$dst_file"; then echo -n "- $delinfo" fi fi done < <(find "$dst_path" -print0) 

As you can see I use echo and ls to display changes.

Источник

Оцените статью
Adblock
detector