Move first n files into another directory in Centos Linux

To move the first 20 files from one directory to another in CentOS Linux, you can use the combination of ls, head, and xargs commands. Here's a step-by-step guide:

1. Open a terminal on your CentOS Linux system.

2. Navigate to the source directory where the files are located. Use the cd command to change to the desired directory. For example, if your source directory is /path/to/source_directory, run:

  • #cd /path/to/source/directory

3. To ensure that you only select files (not directories) for moving, you can use the ls command with the -p option, which appends a slash to the end of directories. Then, use grep to filter out directories and keep only the files. Pipe the output to head to get the first 20 lines (i.e., the first 20 files), and then use xargs to move these files to the destination directory.

Assuming the destination directory is /path/to/destination_directory, run the following command:

  • ls -p | grep -v / | head -n 20 | xargs -I {} mv {} /path/to/destination_directory/

Explanation of the command:

  • ls -p: Lists the files in the source directory with a slash appended to directories.

  • grep -v /: Filters out the directories, keeping only the files.

  • head -n 20: Selects the first 20 lines (files) from the output.

  • xargs -I {} mv {} /path/to/destination_directory/: Uses xargs to execute the mv command for each file listed in the output of the previous commands, moving them to the destination directory.

Please make sure to replace /path/to/source_directory and /path/to/destination_directory with the actual paths to your source and destination directories. Also, be cautious while using mv to move files, as it can overwrite existing files with the same name in the destination directory. Always double-check before executing such commands. 

Comments