Read/Write Files

Creating a File

touch

touch <file>

This will create an empty file if it doesn’t already exist. If the file exists, the command will update the file’s timestamp.

cat

cat > <file>

This will create a file (if it doesn't exist) and allow you to input text directly into it. Press Ctrl+D to save and exit the input mode.

echo

echo <Input> > <file>

This will create a new file or overwrite the content of the specified file with the given input. The file content is replaced completely.

printf

printf <Input> > <file>

Similar to echo, but offers more control over formatting (e.g., new lines, tab spaces, etc.). It will overwrite the content of the file.

Modifying a File

Accessing the Entire File

vi <file>        # A highly customizable, command-line based text editor. It can be tricky for beginners but very powerful once mastered.
vim <file>       # An improved version of vi. It has more advanced features and is widely used for programming.
nano <file>      # A simple, user-friendly command-line text editor. Great for beginners. It displays helpful keyboard shortcuts at the bottom.
gedit <file>     # A graphical text editor for the GNOME desktop environment. It is easy to use and suitable for casual editing.

Step-by-Step Modification

echo <Input> >> <file>     # Appends the input to the end of an existing file, without overwriting it.
printf <Input> >> <file>   # Similar to echo, but allows for more complex formatting. It appends to the file, keeping the existing content intact.

Example

printf "Name: John Doe\nAge: 30\nLocation: New York\n" > info.txt

This creates a file called info.txt and writes the formatted text into it. The ensures that each piece of information is on a new line.

printf "Occupation: Software Developer\nHobbies: Reading, Hiking\n" >> info.txt

This appends additional lines to the existing file without overwriting the previous content.

The file content will be:

Name: John Doe
Age: 30
Location: New York
Occupation: Software Developer
Hobbies: Reading, Hiking

Last updated