1. Overview

In Linux, manipulating files is an important task. From beginners to experienced system administrators, moving files from one location to another is a common operation. One scenario that might arise is moving a specific number of files from a directory.

In this tutorial, we’ll explore how to efficiently move the first n files from one directory to another.

2. Using the Graphical User Interface

Before we proceed, let’s note that we’ll use projects as the source directory that contains the files to move. Meanwhile, we’ll use the destination directory as the directory to move the first n files to.

Moving files using the graphical user interface in Linux entails working with a file manager like Nautilus in GNOME, or some other, depending on the installed desktop environment. This approach is practical when dealing with only a few files since moving many files manually is inefficient. Also, it’s convenient for beginners since it allows them to visually interact with the files they intend to move.

To begin, we need to open the file manager. In this case, we’ll demonstrate using Nautilus. After this, let’s navigate to the projects directory, which contains the files we’re interested in moving:

Files selection

 

Next, let’s click on the first file we want to move, press and hold the Shift keyboard key, and then click on the last file we want to move. This selects a range of files from the first file to the last. However, if the files to move are not listed consecutively, we can hold down the Ctrl key and click on each file individually to select it.

Once we select all the desired n files, let’s right-click on one of the files and click on the Move to option from the menu that appears to begin the move. After selecting Move to, the file manager prompts us to choose the destination directory to move the selected files to:

Destination directory

Here, we navigate to the destination directory and click the Select button to move the selected files.

3. Using the Command Line

Alternatively, we can opt to use the command line. By using this approach, we can automate repetitive tasks and also move files efficiently when dealing with many files.

3.1. Combining the mv, ls, grep, and head Commands

In this approach, we’ll use a combination of the mv, ls, grep, and head commands to move files from the current directory to a directory named destination:

$ mv $(ls -p | grep -v / | head -5) ../destination

Let’s break this command down:

  • ls -p – this command lists the contents of our current directory. Meanwhile, the -p option appends a slash (/) to the end of all directory names, which helps distinguish directories from regular files.
  • | – this pipe symbol redirects the output of the command to its left as input of the command to its right
  • grep -v / – filters the output of the ls -p command. To explain, -v / instructs grep to discard any entry containing a slash. Hence, every directory is filtered out, leaving only regular files in the output.
  • head -5 – selects the first five lines of the previously filtered output, corresponding to the first five non-directory files in the current directory
  • mv $(…) – this part of the command utilizes command substitution to substitute the output of a command. In this case, it’s substituting the output of ls -p | grep -v / | head -5. This output is simply a list of the first five regular files.
  • ../destination – represents the location to move our files to

The above command selects the first five files, excluding directories, and moves them to the destination directory one level above the current directory.

3.2. Combining the mv, find, sort, head, and xargs Commands

In this next approach, we’ll combine the find, sort, head, xargs, and mv commands:

$ find . -maxdepth 1 -type f | sort | head -5 | xargs -I {} mv {} ../destination

Here’s the breakdown:

  • find – searches for files and directories within a specified directory
  • . – specifies the current directory as the starting point of the search
  • -maxdepth 1 – limits the search to only the current directory ignoring the subdirectories. To clarify, this ensures that only files directly within the current directory are considered.
  • -type f – ensures that the search includes only regular files and not directories
  • | sort – the pipe symbol (|) redirects the output from the previous find command to the input of the sort command. The sort command then sorts the list of files the find command returns in alphabetical order.
  • | head -5 – the pipe symbol (|) redirects passes the sorted list to the head command. Here, the head command selects the first five lines from this sorted output.
  • | xargs -I {} mv {} ../destination – the pipe symbol (|) then redirects the output from the head command to xargs. Then, xargs takes each line of input and passes it as an argument to the specified command, in this case, the mv command. Specifically, –I {} represents a placeholder ({}) for each line of input. After that, the mv command moves each file represented in the {} to the specified directory, in this case, the destination directory.

Similar to the previous command, this command also looks for regular files in the current directory. It captures the first five and moves them to the destination directory.

3.3. Using a Bash Script

Creating a Bash script ensures flexibility and automation in the case of repetitive tasks. To demonstrate, let’s create a script.sh file and paste this content:

#!/bin/bash

# Define the source directory
source_directory="./"

# Define the destination directory where files will be moved
destination_directory="../destination"

# Define the number of files to move
num_files=5

# Initialize a counter to keep track of the number of files moved
count=0

# Iterate over the files in the source directory
for file in "$source_directory"*
do
    # Check if the regular file exists
    if [ -f "$file" ]; then
        # Move the file
        mv "$file" "$destination_directory"
        
        # Increment the counter
        ((count++))
        
        # Check if the desired number of files have been moved
        if [ "$count" -eq "$num_files" ]; then
            echo "Moved $count files."
            break
        fi
    fi
done

echo "Moving of files is complete."

Let’s break this down:

  • source_directory=”./” – defines the location of the files to move (which is the current directory in this example)
  • destination_directory=”../destination” – defines where to move the files to
  • num_files=5 – sets 5 as the number of files to move
  • count=0 – this counter monitors the number of files moved, starting from 0
  • for file in “$source_directory”* – initiates a loop that iterates over each file present in the source directory
  • if [ -f “$file” ]; then – checks whether the current item in the loop is a regular file and not a directory
  • mv “$file” “$destination_directory” – if the file exits and is not a directory, it’s moved to the destination directory with the help of the mv command
  • ((count++)) – increments the count value every time the script moves a file
  • if [ “$count” -eq “$num_files” ]; then – inspects if the number of files moved (count) is equal to the desired number of files to be moved (num_files)
  • echo “Moved $count files.” – this command displays the number of files that have been moved
  • break – this command exits the loop once the targeted number of files (num_files) have been moved
  • echo “Moving of files is complete.” – this line prints a message indicating that the file moving operation is complete after the loop completes

Next, let’s execute the Bash script:

$ bash script.sh
Moved 5 files.
Moving of files is complete.

When we run this script, we need to change the source_directory and destination_directory paths with the actual paths to our source and destination directories. Additionally, we need to modify the num_files variable to the exact number of files that we want to move.

4. Conclusion

In this article, we explored how to move the first n files. Whether we’re moving files for backup, organization, or any other reason, understanding how to move the first n files efficiently is valuable.

We discussed various approaches that we can use to accomplish the task at hand. These include using the graphical user interface, executing one-line commands from the command line, and creating Bash scripts for multi-line instructions and repetitive tasks. Every option is valid, and selecting which one to use will depend on our preferences and requirements.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.