Learning Linux- File & Text Manipulation
Beginner’s Guide to Learning Linux/Ubuntu
While using Linux, one will often have to work in the terminal only. It is therefore important for a user to know some basic Linux Commands for file & text manipulation. In this article, we will look into such commands on Ubuntu distro.
If you are new to Linux, check out my article on Learning Linux- Basic Commands first.
Viewing a Text File
To look into the contents of a text file, the command used is:
cat <path of file>
If the file is in the current directory, the following command may be used instead:
cat <file name>
In order to view the start of the file, use the command:
head <path of file>
By default, it shows the first 10 lines of the file. To change the number of lines displayed -n flag is used as follows:
head -n 2 <path of file>.
To view the end of a file, the command used is:
tail <path of file>
By default, it shows the last 10 lines of the file. To change the number of lines displayed -n flag is as follows:
tail -n 2 <path of file>
Editing a Text File
To modify the contents of a text file, a text editor is used. The easiest and common one being nano. The command used to open the file is:
nano <path of file>
Once the file is modified CTRL-O is used to save the changes, followed by CTRL-X to exit from the editor.
Searching a Word in File
To search a word within a file type in terminal:
grep <search word> <path of file>
In order to search a word with all files in a directory, use the command:
grep <word> <path of file/*.txt>
As an example:
grep Daisy ~/Desktop/*.txt
Input/Output Redirection
Using Redirection in Linux, users can change the standard input-output devices. Using Output Redirection instead of displaying the contents on the screen, text output can be saved in a file. Similarly, using Input Redirection the contents of a file can be written onto the screen or attached with another application like Email.
The symbol used for Output Redirection is ‘ > ’. To write redirect output from screen to a file, the command used is
echo <'Message'> > <path of file>
This will create a new file if it is already not present. In case the file is present, its contents would be erased and the new message will be overwritten. In order to append the new message into the file, use >> operator as follows:
echo <'Message'> >> <path of file>
The symbol used for Input Redirection is ‘ < ’ and can be used as follows:
cat < <path of file>
To redirect errors the operator 2> is used. Example, if a user wants to save error messages in a program my program into the file error.txt, the following command will be used:
myprogram 2> <error.txt>
Conclusion
These were some basic Linux commands for File & Text manipulation. Practice is the only way a user can learn these commands efficiently. So do try file handling on your Linux machine, and share your learning experience in the comments.