Working with Files
Text Editor
A text editor is used for editing text files.
Various text editors are:
- Notepad++
- Sublime Text
- gEdit
- Visual Studio Code etc..
Nano
Nano is an easy to use command line text editor for Unix and Linux-based operating systems.
Open file
To open a file with nano, pass the filename as an argument.
Updating File
Add the text of the file in the middle of the editor.
Saving File
To save a file,
Exit Nano
To exit from nano editor,
Viewing File Contents
To view file Contents:
Filtering & Output Redirection
Filtering
We can filter the contents of a file using the following filter commands.
head
tail
grep
head
Used to print top N lines of a file.
By default, it will print the first 10 lines.
Syntax:
Example:
tail
Used to print last N lines of a file.
By default it will print the last 10 lines.
Syntax:
Example:
Counting
Word Count
Piping
Pipe is used to combine two or more commands
Output of one command is passed as an input to the command followed and so on.
Using ‘|’
Syntax:
Example:
Grep
Searches a file or files for lines that have a certain pattern.
Syntax:
Example:
Example 1
Number of lines that contain the word morning in the given file.
Example 2
Occurrences of the word "morning" in the given file from the lines 10 to 15
Output Redirection
">" takes the standard output of the command and redirects it to the file.
Syntax:
Example:
Compressing & Uncompressing Files
File compression is a reduction in the number of bits needed to store the data of a file.
- Files are stored in such a way that, it uses less disk space than all the individual files and directories combined
- Advantages of compressing files are:
taking less disk space
- easier and faster transmission
Commonly used file formats for the compressed files:
gzip
zip
tar
tar
We can use tar to compress files & directories
Compression
Syntax:
Example:
Extract/ Uncompress
Syntax:
Example:
zip
It is used to package all the files into one file with .zip extension
Syntax:
Example:
unzip
The unzip command extracts all files from the specified ZIP archive
Syntax:
Example:
Summary
Command | Description |
---|---|
head | Used to print top N lines of a file |
tail | Used to print last N lines of a file |
wc | Used to find out number of lines, word count and characters count in the files |
grep | Searches a file or files for lines that have a certain pattern |
tar | Used to compress files & directories |
zip | Used to package all the files into one file with .zip extension |
unzip | It extracts all files from the specified ZIP archive |