Bash File & Directory Operations

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

File and directory operation refers to the fundamental task that enables the user to manage and manipulate the file system efficiently. It is not only important for the user but also for the developers to understand the command-line operations for automation.

Let’s see some necessary files and directory operations in bash.

Open Text File in Bash

Opening a text file generally refers to creating and reading out the file from the command line without editing the file. Let’s see some methods to open a file below:

Command-line Interface

  1. To open an existing file, use a very powerful command called cat. You use the redirection “>” operator to create a new file and add new text to it. Then you can write content in it. But if the file already exists with the filename, then the text will be overwritten. The cat command with redirection is used in cat > [filename].

    Creating file cat bash operatorHere a new file named ‘mealtime’ has been created. Let’s see if the content of ‘mealtime’ whether saved or not.

    cat mealtime

    Open a file with cat command bash operatorIn this process, you can create and open a file.

  2. If you want to read a large file then you can use the less command following the file name.  This is the fastest command for reading a file. It won’t show you the whole file instead it shows less content in one line at a time. When you want to see the next line, press the ENTER key.Open with less bash operatorScroll down the file

    With less command, you can see a single line by pressing the ENTER button and to exit from the file view,  press the “q” button.

  3. Like the less command, the more command is also used for displaying the large files. But this command shows the files on multiple pages.

    Open file with more operatorThe more command shows a single page when one presses the ENTER button.

Command Line Text Editor

You can also create a file using a text editor. For example, use the nano command following the file name and press ENTER. This will create an empty file in the name given to it.

Create text editor file with bash operatorTo write out something or save the edit to the file, press CTRL+O and then ENTER to save the changes, after that press CTRL+X to exit.

Save the text editorLike nano, you can use vi and vim text editors to open files.

Graphical User Interface Text Editor

To open a text file from the GUI text editor, use the gedit command following the filename as below:

gedit filename
Open file with gedit GUI bash operatorExcept for showing the output in the terminal, it shows the output in the gedit Text editor.

You can open other existing files from the gedit text editor. Click on the open button you can access other directories and files using the gedit text editor.

Edit Text File in Bash

Editing text files refers to the process of writing, removing, appending, and modifying the content of the file. Some key editing aspects are:

Writing to Files in Bash

Some methods to write into a file have been shown below:

Using Nano

  1. To write to a file, you can use the nano text editor. Also, you can use the vi and vim text editor. For example. open a file with the nano command following the file name such as:

    nano countries.txt
    Before writing into a empty file

  2. Now, write some content in it.Completed the writing
  3. After writing the file, save the content by pressing CTRL+O and ENTER. It saves the file. To exit from the text editor, press CTRL+X.

Using Redirection Operator

You can also write to a file, using the redirection operator (>). For this purpose, you can use the echo and printf commands. Here, I will show the cat command with the redirection to write a file using heredoc. It will allow you to write multiple lines in the file from the terminal.

cat <<EOF> countries2.txt

It will save the lines that you write in “countries2.txt” until EOF is found in your writing.Heredoc to write file in bash operator

Write in Multiple Files

If you want to write the same text in multiple files, then you can use the tee command. Run the following command:

echo -e “Hello World. \nLet’s start from the beginning.” | tee combo.txt
EXPLANATION

The echo command prints the text for the standard out. “| is the pipe that takes the output of the left and then passes as the input for its right. The tee command will take the standard input and write it into the standard output of the following.

Write with the tee bash operating command

To interpret the backslash-escaped character (\,\n) use the -e option with the echo command.

Remove Line from File in Bash

To remove a specific line from a file without opening the file, use the sed command. Using this command you can remove a range of lines, the lines that start with a word, and also you can remove empty lines.

For example,

sed -i ‘3d’ mealtime
EXPLANATION

sed stands for the stream editor which transforms the input file. 3d means it will delete the third line from the intro.txt file. The -i option removes the line from the file.

Remove a line from a file

The -i option used in the command modifies the original file. If you want to see only the output without any modification of the original file then don’t use the “-i” option.

If you want to know the line and word count of a file then you can use the wc command. Use the command wc -lwc <filename> to count the lines, words, and characters of files.

Word and line countIn the output, it is shown that there are 14 lines, 18 words, and 113 characters in the text file.

Appending Files in Bash

Appending to a file is a process of adding new lines or content to the existing files. In this process, without changing the previous content, it adds a new line at the end of the file. Let’s see some methods to append in a file.

1. Redirection Command

  1. To append a new line to the file, you can use the echo command with the redirection operator (>>). The file name will be specified after the redirection operator. For example, run the following command:

    echo “All days are added” >> weekdays

    It will add “All days are added” at the end of the file. Let’s see the content of weekdays now using cat weekdays.

    Append with echo bash operatorFrom the output, you can see at the end of the file the new line has been added.

  2. To increase the output flexibility and print formatted form, use the printf command with the redirection operator.
    printf “My name is %s.\n” $(whoami) >> intro
    EXPLANATION

    %s indicates the format specifier for the string and is replaced by the command substitution $(whoami) and whoami replaces it with the name of the current user name.

    Append using printf

  3. If you want to append multiple lines to a file then you can try to use here doc with redirection operator. Run the following code:

    cat <<EOF>> intro
    >My current working directory is $PWD
    >Today is $(date)
    >EOF

    Append using cat bash operatorIt is beneficial to use this when you want to append multiline. cat command reads the heredoc and then it redirects the standard output to a specific file.

2. Tee Command

Tee is the command that reads content from the standard input and writes it into the standard output and other files. It is mainly used when you want to append text into multiple files. Here’s an example command to understand the syntax:

echo “Some colors have been added.” | tee -a colors.txt
EXPLANATION
The -a option is used to append text at the end.
Tee command

If you do not use the “-a” option then it overwrites the file. By using the option it just appends the content at the end of the file. You can also use multiple files with this command:

echo “Some colors have been added.” | tee -a file1.txt file2.txt file3.txt

And it will append the line in all the files.

Truncating File

Truncate is a process to reduce the size of a file without deleting the actual file. It is a useful and faster process because new file permission and ownership are not needed. I will show some methods for truncating a file.

Using Truncate Command

Using the truncate command you can truncate it. The command follows the structure of truncate -s [file_size] filename. Copy the following command to run.

truncate -s 0 hello.txt
EXPLANATION
The “-s 0” indicates that setting the file size to 0 byte makes it an empty file.
Truncate with truncate bash operatorYou can set the file size according to your preference.

Using Redirection:

  1. Use the redirection operator (>) following the file name (> [filename])Redirection truncation

    The command > [filename] redirects the output to the specified file but there is no command before the operator for that reason it shows an empty file after truncation.

  2. You can use the echo command with the redirection operator to remove the content from the file. Copy the command and replace the filename with your preferred one.

    echo -n > meallist.txt
    EXPLANATION

    The -n option instructs the echo command not to add a new line which redirects to the specified file with an empty string.

    Truncating file with echo command

    To truncate the file you can use the “:” operator followed by the redirection operator and file name.

    Null bash operator truncate The null operator redirects as an empty command to the specific file and truncates that file.

Conclusion

In this article, the basic types of operations which are open and edit files have been shown. The operations of files mainly provide a powerful set of tools for manipulating the content of files directly from the command line. Hope the article will help you to implement the basic operations of files in bash.

People Also Ask

How can I read a file line by line?

To read a file you can use cat, less, and more commands. But for larger files use a loop to iterate over line and read each line. Copy the following code to read a file line by line.

#! /bin/bash
filename='File.txt'
n=1
while read line; do
echo "Line No. $n : $line"
n=$((n+1))
done < $filename

In the bash script replace the File.txt with your preferred file name. This will iterate over the line and show the line number.

How do I edit files in vim text editor?

To edit a file with vim, use the vim command with the filename in this process vim filename. Then it will open the file in the editor and can edit the file. But for that you need vim text editor to be installed if not available, then install it with any package manager.

How can I truncate a file into a specific size?

You can use the truncate command to specify the size. For example, if you want to modify a file to n  bytes then use the command truncate -s n filename and replace the filename and n with the one that you wanted to modify.

Can I use rm command to remove a line from a file?

No, the rm command is used to remove a file, not a line. If you use the rm command then it will remove the entire file. To remove a line you can use the sed command.

Related Articles


<< Go Back to Bash Files and Directories | Bash Scripting Tutorial

2.3/5 - (3 votes)
Afia Zahin Oishi

Assalamualaikum, I am Afia Zahin, completed my graduation in Biomedical Engineering from Bangladesh University of Engineering and Technology, currently working as a Linux Content Developer Executive at SOFTEKO. A high achieving professional with a strong work ethic and able to work in a team in order to consistently achieve my goal and build my skillset. Able to handle difficult problems with patience and swift decision-making. Read Full Bio

Leave a Comment