0% found this document useful (0 votes)
6 views

Linux Commands

The document provides an overview of essential Linux commands for file and directory management, including commands like mkdir, rmdir, cd, pwd, file, ls, cat, more, and less. It details the syntax, options, and examples for each command, explaining their functionalities such as creating, removing, navigating, and displaying files and directories. Additionally, it covers basic file operations like finding, copying, moving, and linking files using commands like find, cp, mv, rm, and ln.

Uploaded by

thirosul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Linux Commands

The document provides an overview of essential Linux commands for file and directory management, including commands like mkdir, rmdir, cd, pwd, file, ls, cat, more, and less. It details the syntax, options, and examples for each command, explaining their functionalities such as creating, removing, navigating, and displaying files and directories. Additionally, it covers basic file operations like finding, copying, moving, and linking files using commands like find, cp, mv, rm, and ln.

Uploaded by

thirosul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

1

Linux commands
 File and directory Management Commands:
File and directory management commands in Linux are used to organize, access, and manipulate
files and folders.
These commands are: mkdir, rmdir, cd, pwd, file, ls, cat, more, less.

1) mkdir command:
To create a directory in Linux you have to use mkdir command which stands for make directory.

Syntax:

$mkdir [option] <directory-name>

Option Description
-p Creates parent directories if they don't exist.
-m Sets the file modes, i.e., permissions, for the new directory. (Ex- mkdir -m777 gfc)
-v Displays a message for each created directory.
--version Displays the version number and information about the license and exits.
-Z Set SELinux security context of each created directory.
--help Displays help with information about mkdir options.

Example: Create single directory.

$mkdir gfcct

Example: With the help the of mkdir command user can create number of directories at a time.

$mkdir A B C D

Example: We can create directory in specific path.

$mkdir /home/viraj/gfc

2) rmdir command:
The Linux rmdir command which stands for remove directory and these command removes empty
directories only.

Syntax:

$rmdir [option] <directory-name>

Option Description
--ignore-fail-on-non-empty It prevents the errors if the directory is not empty.
-p or --parents It will removes the directory and its parent directories if they are empty.
-v or --verbose It helps in displaying the message for each directory that is removed.
--help It will displays the helpful information and exits.
--version It displays version information and exits

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


2
Example: Remove empty/single directory.

$rmdir gfcct

Example: With the help the of rmdir command user can remove number of directories at a time.

$rmdir A B C D

Example: We can remove directory in specific path.

$rmdir /home/viraj/gfc

3) cd command:
The cd command which stand for change directory it’s used for to change directory. The cd
command take argument as directory name that you want to change.

Syntax:

$cd <directory name>

Example:
$cd gfc

Tabular Summarization:

Use Cases Description Examples / Notes


Navigate to a Specific cd /path/to/directory cd /var/log
Directory
Go Back to the Home cd or cd ~ cd or cd ~
Directory
Navigate to the Previous cd - cd - from /var/log returns
Directory to /home/user/Documents
Navigate to the Parent cd .. cd .. from /home/user/Documents moves
Directory to /home/user
Handle Spaces in Names Use quotes or escape cd "My Documents" or cd My\ Documents
spaces
Access Hidden Directories Include dot in path cd .config
Navigate to Root Directory cd / Navigate to the root directory.
Chain Commands cd /path/to/directory Changes directory and lists contents.
&& ls

4) pwd command:
The ‘pwd,’ which stands for “print working directory”. The pwd command in Linux displays the
current working directory in the terminal window.

Syntax:

$pwd [option]

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


3

Option Description
-L print the value of $PWD if it names the current working directory
-P print the physical directory, without any symbolic links

Example:
$pwd
Result:
/home/viraj

5) file command:
The file command is used to determine the file type. It does not care about the extension used for
file. It simply uses file command and tell us the file type. It has several options.
The file type can be displayed in a human-readable format (e.g., ASCII text) or as a MIME
type (e.g., ‘text/plain; charset=us-ascii‘).
Syntax:

$file [option] <file-name>

Option Description
-b, --brief This is used to display just file type in brief mode
* Command displays the all files’s file type.
[range]* To display the file type of files in specific range.(Ex- file [a-z]*, file [a-e]*)
-i To view mime type of file.
-z Try to look inside compressed files. (Ex- file -z flash.tar.gz )

Example:
$file file.txt

Result:
file.txt: ASCII text

6) ls command:
The ls command in Linux lists files and directories in a specified directory. It also provides
information about the files and directories, such as their permissions, sizes, and modification dates.
Syntax:

$ls [option] <file-name>

Commonly Used Options in `ls` command in Linux


Options Description
-l displays detailed information about files and directories.

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


4
-a Represent all files Include hidden files and directories in the listing.
-t Sort files and directories by their last modification time, displaying the most recently modified
ones first.
-r which is used to reverse the default order of listing.
-S Sort files and directories by their sizes, listing the largest ones first.
-R List files and directories recursively, including subdirectories.
-i known as inode which displays the index number (inode) of each file and directory.
-g known as group which displays the group ownership of files and directories instead of the
owner.
-h Print file sizes in human-readable format (e.g., 1K, 234M, 2G). (Ex- ls -lh)
-d List directories themselves, rather than their contents.

Example: To show list of file and directory


$ls

Example: To show all list of file and directory (hidden also) by using –a option.
$ls -a

Example: To displays detailed information about files and directories by using –l option.
$ls -l

Note: These three commands used for Display file- (cat, more, less)

7) cat command:
The cat command is the most universal and powerful tool. It is considered to be one of the most
frequently used commands. It can be used to display the content of a file, copy content from one file to
another, concatenate the contents of multiple files, display the line number, display $ at the end of the
line, merge, and manipulate file contents.
Syntax:

$cat [option] <file-name>

Options Description
-n Show the number for each line in file
-A Show all
-b number-nonblank, It shows the total non-empty output lines. Also, it
overrides -n.
-E It shows the $ symbol at the completion of all lines.
-s It suppresses redundant empty output lines.

Example: Create file by cat command with > operator and file-name then write the file info and use Ctrl+D
or Ctrl+Z for exit.
$cat > file.txt
Welcome to Linux

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


5
Example: To display file content.
$cat file.txt
Example: To View the Content of Multiple Files in Linux (If we have two files , file1 and file2.)
$cat file1.txt file2.txt
Example: To copy content from older to new file.
$cat file1.txt > file2.txt
Example: To concatenate contents of multiple files into one.
$cat file1.txt file2.txt > file.txt
Example: The 'cat' command with double greater than sign (>>) append (add something in the last of a file).
$cat >> file.txt
In the Linux shell terminal shell programming is possible.

Example: The 'cat << EOF ' option displays an end marker at the end of a file.

$cat > aa.txt << EOF

8) more command:
The more command in Linux is a command-line utility that allows users to view text files one page
at a time. The more command is often used when dealing with large files that cannot be viewed in their
entirety on a single screen. It is a simple, yet powerful tool included in most Linux distributions.

Syntax:

$more [option] <file-name>

Options Description
-num Limits the line displayed per page.
-d Displays user message at right corner, Navigation Help
-f Displays long lines without wrapping them, showing the file in correct
format.
+/String name It helps to find the string.
+linenum Used to display the content from a specific line.
-p Clear and Display
-u removes underlined characters, which can be useful when viewing text
files

Example: Display content of file.txt

$more file.txt

Example: display the content from a 10 line of file

$more +10 file.txt

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


6
Example: display the content 10 line of file

$more -10 file.txt

Example: removes underlined characters of file

$more -u file.txt

9) less command:
The less command is same as more command but include some more features. The less command
display information to once screen at a time, you can execute less command by entering command name
followed by file name.
It automatically adjust with the width and height of the terminal window, while 'more' command cuts
the content as the width of the terminal window get shorter

Syntax:

$less [option] <file-name>

Options Description
-p Searching for a pattern
-E Automatically exit when reaching the end of the file.
-f Force non-regular files to be opened.
-F Exit if the entire file can be displayed on the first screen.
-g Highlight the string that was found by the last search command.
-G Suppress highlighting of search matches.
-i Ignore cases when searching.
-N Display line numbers.
-p pattern Start at the first occurrence of the specified pattern in the file.
+/pattern Search for a String
-s Remove Multiple Blank Lines

Example: Display file

$less file.txt

Example: Searching for a pattern in file

$less –p “Linux” file.txt

Example: To Display line numbers each line in file.txt.

$less –N file.txt

Example: To remove Multiple Blank Lines in file.txt

$less –s file.txt

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


7
 File and Directory Operations:
In Linux, "File and Directory Operations" refers to the actions you can perform on files and directories
within the file system - deleting, moving, renaming, copying and accessing them using various commands in
the terminal.

Basic Operations: find, cp, mv, rm, ln.

1) find command:
The find command helps us to find a particular file within a directory. It is used to find the list of
files for the various conditions like permission, user ownership, modification, date/time, size, and more.

Syntax:

$find [path] [options] [expression]

option Description
-name Searches for files with a specific name.
-type Specifies the type of file to search for (e.g., f for regular files, d for directories).
-print Displays the path names of files that match the specified criteria.
-empty Finds empty files and directories.
-delete Deletes files that match the specified criteria.
-group name Searches File for specific Group.
-user name Searches File for specific User.
-perm Searches file for certain permission sets

Example: To find simple way to find file.txt

$finde file.txt

Example: To find a file named “file.txt” in the home directory, you would use:

$find ~ -name "file.txt"

Example: To find a file by type option

$find ~ -type d

Example: Find empty files

$find ~ -type d -empty

Example: Find all files which have a 777 permission.

$find * -perm 777

Example: Find all files belong to specific user

$find * -user viraj

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


8
2) cp command:
The cp command is used to copy file and directory. This command creates a copy of the
`source_file` at the specified `destination`. If the destination is a directory, the file is copied into that
directory.

Syntax:

$cp [options] <Source-file> <Destination-file>

option Description
-i (Interactive prompt) ask for confirmation before overwrite.
-f (Force) if an existing destination file cannot be opened, remove it and try again.
-u Copy only when the SOURCE file is newer (new) than the destination file.
-v (verbose) Display Message about what being done.

Example: To copy any txt file in directory.

$cp file.txt MyFile

Example: To copy any txt file in directory by use –v option.

$cp -v file.txt MyFile

2) mv command:
The mv command is used to move files and directories. Also used to rename.

Syntax:

$mv [options] <Source-file> <Destination-file>

option Description
-i (Interactive prompt) ask for confirmation before overwrite.
-f (Force) if an existing destination file cannot be opened, remove it and try again.
-u Move when the SOURCE file is newer (new) than the destination file.
-v (verbose) Display Message about what being done, print source and destination files.

Example: To move multiple file in directory.

$mc -v file.txt file1.txt file2.txt MyFile

Example: To mv txt file into another txt file that time rename.

$cp -v file.txt file1.txt

Note: When you mv source-file to destination-file that time rename source-file as a name of destination-file.
If destination-file is not available that time automatically destination-file is crated.

Example: Update -move when main.c is newer to bakup directory.

$ mv –u main.c bakup

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


9
4) rm command:
The rm command removes complete directories, including subdirectories and files.
Syntax:

$rm [option] <directory-name>

Option Description
-f Forces the removal of all files or directories.
-i Prompts for confirmation before removing.
-I Prompts once before removing more than three files or when removing recursively.

-r Removes directories and their content sub directory.


-d Removes empty directories.
-v Provides a verbose output.
--help Displays the help text.
--version Displays the command version.

Example: Remove empty/single directory use –d option.

$rm -d gfcct

Example: With the help of rmdir command user can remove number of directories at a time.

$rm –d A B C D

Example: We can remove directory in specific path and removes directories and their content sub directory.

$rm –r /home/viraj/gfc

5) ln command:
The ln command is used to make links between files. ln command used to link one file to another
file. That allow to access by different name.

There are two types of links:


1) Hard Link
2) Soft Link or Symbolic Link

1) Hard link:
The ln command creates hard link by default or hard link create two different name for same file. ln
command used without any option to create hard link.

Syntax:

$ln <Original-File-Name> <Link-Name>

Example:

$ln first.txt one.txt

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


10
Note: Whenever we remove original file then REFERENCE to HARD link file will EXIST .i.e. if we
remove first.txt then also one.txt file exist with contents.

2) Soft or Symbolic link:


To create symbolic Link –s option is used with ln command having two arguments used
First argument is name of original file and second argument is name of newly added link file.
The ls command operation lists out both file names. But only one physical path will be exist (means
both file have a same path).

Syntax:

$ln -s <Original-File-Name> <Link-Name>

Example:

$ln –s first.txt one.txt

Note: Whenever we remove original file then NO REFERENCE to symbolic link file will EXIST. Because
both files are holds same path/location.

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


11
 Printing the files:
In Linux, printing commands are used to print a file or output. Printing from a Linux terminal is a
straightforward process.

These three basic commands are:


lpr, lpq, lprm

1) lpr command:
The lpr or lp which stands for Line Printer. These commands are used to print files from the
command line to a printer (printer connected to system). It is part of the Common UNIX Printing System
(CUPS).

Syntax:

$lpr [option] <file-name>

Option Description
-num Sets the number of copies to print from 1-100
-r Named print file should be deleted after printing

Example: Prints 10 copies of Doc.txt file on printer by use –num option.

$lpr –10 Doc.txt

Example: Prints multiple file i.e. file.txt, python.doc and linux.pdf

$lpr file.txt python.doc linux.pdf

2) lpq command:

The lpq which stands for Line Printer Queue. These commands are used to show printer queue
status, List out the pending printing jobs on Printer in the queue.

Syntax:

$lpq [option]

Option Description
-a Reports list of pending jobs on ALL PRINTERS connected to system

Example: Display pending queue.

$lpq

Rank Owner Job Files


active root 483 file.txt
2nd viraj 484 /tmp/myfile.txt
3rd viraj 485 linux.pdf

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


12
3) lprm command:
The lprm which stands for Line Printer remove. These commands are used to remove print requests
from the Print Queue.

Syntax:

$lprm <Job-ID>

Example: To remove a print job from the queue for your default printer.

$lpq

Rank Owner Job Files


active root 483 file.txt
2nd viraj 484 /tmp/myfile.txt
3rd viraj 485 linux.pdf

$lprm 484

The user viraj has job id 484 is removed their print job from the printer queue.

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


13
 Filter Commands & Editor:
A filter command in Linux is a command that modifies standard input and produces standard output.

Filters can be used to perform a variety of operations, such as:


head, tail , pr, cut, paste, sort, uniq, tr, grep, egrep, fgrep, sed.

1) head command:
The head command is used to display N number of lines of the top of the file. When user execute head
command with file name that time display by default 10 top lines of that file.

Syntax:

$head [option] <file-name>

Option Description
-n Specifies top n number of lines to be displayed.
-c It is used to display some character that time use within number. (Ex- $head –c5 file.txt)
-v To print header information verbose always.

Example: Prints top 5 lines in Doc.txt file by use –n option.

$head –n5 Doc.txt

Example: Prints first line of first 5 character in Doc.txt file by use –c option.

$head –c5 Doc.txt

2) tail command:
The tail command is used to display N number of lines of the bottom of the file. When user execute tail
command with file name that time display by default 10 bottom lines of that file.

Syntax:

$tail [option] <file-name>

Option Description
-n Specifies bottom n number of lines to be displayed.
-c It is used to display some character that time use within number. (Ex- $tail –c5 file.txt)
-v To print tail information verbose always.

Example: Prints bottom 5 lines in Doc.txt file by use –n option.

$tail –n5 Doc.txt

Example: Prints last line of last 5 character in Doc.txt file by use –c option.

$tail –c5 Doc.txt

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


14
3) pr command:
The pr command prepares a file for printing by adding suitable header, footer and formatted text file.
The header shows the date and time of last modification of the file along with the filename and page
numbers.

Syntax:

$pr [option] <file-name>

Option Description
-n Adding Numbers to lines.
-t Omit /remove/ignore the header and footer.
-d Double spaces to the output.

Example:

$pr file.txt

4) cut command:
The cut command in Linux is used for cutting out the sections from each line of files and writing the
result to standard output. It can be used to cut parts of a line by byte position, character, and field. The cut
command slices a line and extracts the text. It is necessary to specify an option with a command otherwise it
gives an error.

Syntax:

$cut [option] <file-name>

Option Description
-b Selects only the bytes specified in LIST (e.g., -b 1-3,7).
-c Selects only the characters specified in LIST (e.g., -c 1-3,7).

Example: To cut range bytes 1-5 in file.txt

$cut -b 1-5 file.txt

Example: To cut without range. to use another way is set 1,3,5 number character of line in file.txt

$cut -b 1,3,5 file.txt

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


15

5) paste command:
The paste command is used to join files horizontally (parallel merging) by outputting lines
consisting of lines from each file specified, separated by tab as delimiter, to the standard output.
When no file is specified, or put dash (“-“) instead of file name, paste reads from standard input and
gives output as it is until a interrupt command [Ctrl-c] is given.

Syntax:

$paste [option] <files>

Option Description
-d The delimiter can be changed to any other character by using the -d
-s We can merge the files in sequentially manner using the -s

Example: To merge 2 file by paste command.

$paste number.txt capitals.txt

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


16
Example: We can merge the files in sequentially manner using the -s

$paste -s number.txt capitals.txt

Example: The delimiter can be changed to any other character by using the -d

$paste -s number.txt capitals.txt

6) sort command:

The sort command is used to sort a file, arranging the records in a particular order. The 'sort'
command sorts the file content in an alphabetical /ascending by default order.

Syntax:

$sort [option] <files-name>

Option Description
-r The sort order to reverse sequence.
-u Removes repeated lines
-n To sort numerically.
-k To sort on a field in a file. i.e. -k 2
-c Check if file is sorted.
-o Places data in a file (override old data )

Example: sort file

$sort capitals.txt

Example: The sort file by reverse order

$sort –r number.txt

Example: To sort numerically

$paste -n number.txt capitals.txt

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


17

7) uniq command:
Linux uniq command is used to remove all the repeated lines from a file. Also, it can be used to
display a count of any word, only repeated lines, ignore characters, and compare specific fields. It is one of
the most frequently used commands in the Linux system. It is often used with the sort command because it
compares adjacent characters.

Syntax:

$uniq [option] <file-name>

Option Description
-d Only output lines that are repeated in the input.
-c Prefix lines by the number of occurrences in the input, followed by a space.
-u Only output lines that are unique in the input.

Example: To remove duplicate lines from `file.txt`, we can use the `uniq` command.

$uniq file.txt

Example: The `-c` option prefixes each line with the number of occurrences in the input.

$uniq -c file.txt

Example: The `-D` option prints all duplicate lines, not just one per group:

$uniq -d file.txt

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


18

Example: To remove duplicate lines using uniq, you should first sort the file and then pipe the output to
uniq. Here’s how you can do it:

$sort file.txt | uniq

8) tr command:
The tr command stands for 'translate'. It is used to translate, like from lowercase to uppercase and
vice versa or new lines into spaces.
It supports a range of transformations including uppercase to lowercase, squeezing repeating
characters, deleting specific characters, and basic find and replace. It can be used with UNIX pipes to
support more complex translation.

Syntax:

$tr [option] SET1 SET1

Option Description
-d This option use to deleting characters.
-t truncates set1
-s replaces repeated characters listed in the set1 with single

Example: To convert `file.txt` into upper case by use `tr` command.

$cat file.txt | tr [:lower:] [:upper:]

Or

$ cat file.txt | tr [a-z] [A-Z]

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


19
Example: To translate white-space characters to tabs.

$cat file.txt | tr [:space:] “\t”

Example: To squeeze a sequence of repetitive characters using -s option.

$ echo "Welcome To Gfc" | tr –s " "

Output:

Welcome To Gfc

Example: To delete specified characters using -d option.

$ echo "Welcome To Gfc" | tr -d W

Output:

elcome To Gfc

9) sed command:
The 'sed' command stands for stream editor. It is used to edit streams (files) using regular
expressions. But this editing is not permanent. It remains only in display, but in actual, file content remains
the same.
Primarily, it is used for text replace (substitution); additionally, it can be used for other text
manipulation operations like insert, delete, search, and more. The sed command allows us to edit files
without opening them. Regular expression support makes it a more powerful text manipulation tool.

Syntax:

$sed [option] {script} <input-file>

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


20

Option Description
-i Edit the file in place without printing to the console (overwrite the file).
-n Suppress automatic printing of lines.
-e Allows multiple commands to be executed.
-f Reads sed commands from a file instead of the command line.
-r Enables extended regular expressions.

Example: To Replacing or substituting string:

$ sed 's/Gfc/GFCCT/' file1.txt

Here the “s” specifies the substitution operation. The “/” are delimiters.

Example: Replace String in Specific Line Using the sed Command

$sed '4 s/socks/sandals/' file.txt

Note:

1) Replacing the nth occurrence of a pattern in a line to Use the ‘/1’, ‘/2’ etc. flags to replace the first,
second occurrence of a pattern in a line.

sed 's/Gfc/GFCCT/2' file1.txt

2) Replacing all the occurrence of the pattern in a line The substitute flag /g (global replacement)

sed 's/Gfc/GFCCT/g' file1.txt

Example: To delete 2 number line in file

$ sed 2d file.txt

Example: Delete Lines Within a Specific Range of Lines Using the sed Command
$sed '2,4d' file1.txt

Example: The -n option disables automatic printing, while the substitute command p instructs sed to print
lines where substitution occurs.

sed -n 's/Gfc/GFCCT/p' file1.txt

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


21
10) grep command:
The 'grep' command stands for “global regular expression print”. grep command filters the
content of a file which makes our search easy. The grep filter finds a file for a specific character pattern and
shows every line that includes that pattern.

Syntax:

$grep [option] {pattern} <file-name>

Options Description
-c This prints only a count of the lines that match a pattern
-h Display the matched lines, but do not display the filenames.
–i enables to search for a string case insensitively in the given file
-l Displays list of a filenames only.
-n Display the matched lines and their line numbers.
-v This prints out all the lines that do not matches the pattern
-e exp Specifies expression with this option. C an use multiple times.
-f file Takes patterns from file, one per line.
-w Match whole word
-o Print only the matched parts of a matching line.

Example: The -i option enables to search for a string case insensitively in the given file.

$grep -i "love" file.txt

Example: We can find the number of lines that matches the given string/pattern by –c option.

$grep -c "love" file.txt

Example: We can just display the files that contains the given string/pattern by –l option.

$grep -l "love" *

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


22
Example: Displaying only the matched pattern by –o option.

$grep – o "love" file.txt

Example: Show Line Number While Displaying the Output Using grep -n

$grep – n "love" file.txt

Example: You can display the lines that are not matched with pattern using the -v option.

$grep – v "love" file.txt

11) egrep command:


The egrep’ stands for “extended grep” and is a part of the grep family of commands used for text
processing and pattern matching in Linux. It is preferred over basic grep when working with extended
regular expressions, as it inherently supports meta-characters without requiring them to be escaped, thus
simplifying complex searches. The ‘egrep‘ command is also known for its speed and efficiency, making it
a popular choice among system administrators and developers.

Syntax:

$egrep [option] {pattern} <file-name>

Options Description
-c This prints only a count of the lines that match a pattern
-h Display the matched lines, but do not display the filenames.
–i Ignores, case for matching
-l Displays list of a filenames only.
-n Display the matched lines and their line numbers.
-v This prints out all the lines that do not matches the pattern
-w Match whole word
-o Print only the matched parts of a matching line.

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


23
Example: The -i option enables to search for a string case insensitively in the given file.

$egrep -i "love" file.txt

Example of egrep same as the above grep command.

12) fgrep command:


The ‘fgrep’ stands for “fixed grep” and part of the grep family, designed to search for fixed
strings rather than patterns defined by regular expressions. The fgrepcommand can be used to search
through one or multiple files, providing results that match the specified string exactly as given.

Syntax:

$fgrep [option] {pattern} <file-name>

Options Description
-c This prints only a count of the lines that match a pattern
-h Display the matched lines, but do not display the filenames.
–i Ignores, case for matching
-l Displays list of a filenames only.
-n Display the matched lines and their line numbers.
-v This prints out all the lines that do not matches the pattern
-w Match whole word
-o Print only the matched parts of a matching line.

Example: The -i option enables to search for a string case insensitively in the given file.

$fgrep -i "love" file.txt

Example of fgrep same as the above grep command.

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


24
 Communication commands:
In Linux, "communication commands" refer to a set of utilities that allow users to interact with each
other directly through the terminal, like sending messages, including commands like "write", "wall", "mesg",
and "talk", which enable real-time communication between logged-in users on the same system, other user
using mail command.
Purpose:
messaging between users on a multi-user Linux system without needing a separate chat application.

1) write command:
The write command in Linux is used to send a message to another user. The write utility allows a
user to communicate with other users, by copying lines from one user’s terminal to others. When you run the
write command, the user you are writing to receives a message in the below format.

Message from yourname@yourhost on yourtty at hh:mm ...

Any further lines the user enter will be copied to the specified user’s terminal. If the other user wants
to reply, they must run write as well. When you are done, type an end-of-file or interrupt character. The
other user will see the message ‘EOF’ indicating that the conversation is over.

Syntax:

$ write user [tty]

Options of Write Command:

Option Description
write username Sends a message to the specified user’s terminal.
write username tty Sends a message to the specified user’s terminal on a specific terminal device.
Ctrl+D Ends the message input session.
mesg y Allows messages from other users (enables write access).
mesg n Disallows messages from other users (disables write access).

Send Messages to Terminal Users:


In this step, we will learn how to send messages to other terminal users on the same system.
First, let's check the list of users currently logged into the system using the who command (to show all the
list of currently logged users).

$who

The following are the some of the examples of write command:

Example 1: For sending a message to a user named `john` on their current terminal, the command looks
as follows:

$ write john
hello john, are you available for a meeting?

CTRL+D

On executing this command the message would be displayed to john user by following manner,

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


25
Message From viraj on john at 12:33.00
hello john, are you available for a meeting?
END-OF-MESSAGE

Example 2: For a send a message to a user named suppose `alice` on a specific terminal (`tty2`). The
command looks as follows:
$ write alice tty2
Hi Alice, please review the latest changes.

CTRL+D

Note-
a) While executing to write the command if it doesn’t operate or if it is disabled, then use mesg
command to turn it on. After which write command will be executed.
b) Recipient must have given permission for incoming messages by mesg command use y or n.
c) Recipient must be logged in else Error message raised

2) mesg command:
The mesg command controls the access to your terminal by others user. It’s typically used to allow
or disallow other users to write to your terminal.
The mesg command is a useful tool for managing message permissions on a Linux system. It
allows users to receive or reject messages sent by other users on the same system

Syntax:

$mesg [option]

Tag Description
mesg To check the current message permission status.
y Allow write access to your terminal.
n Disallow write access to your terminal.

Note- If no option is given, mesg prints out the current access state of your terminal.

Example 1: First, let's check the current message permission status using the mesg command.

$mesg

Result: The output is y indicates that the user is currently able to receive messages.

$is y

Example 2: To deny message receiving, use the mesg n command.

$mesg n

Example 3: To allow message receiving, use the mesg y command.

$mesg y

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


26
3) talk command:
The talk command allows you to start a conversation with another user on the same system or a
remote system, provided that the other user is also running the talk command and has accepted your request.

Syntax:

$talk <user-name> <ttyname>

The talk command takes two arguments:


User-name: The username of the user you want to talk to.
ttyname: The ttyname means terminal name, terminal device of the other user (optional).

Send Messages Using the talk Command

Example 1: First, let's start a talk session with another user. Assuming the other user's username is GFC,
we can start the session like.

$talk GFC

This will send a request to the GFC user, and if they accept the request, the talk session will begin.

Once the session is established, you can start typing your message. Each line you type will be sent to the
other user's terminal in real-time. The other user can also respond, and you will see their messages appear
on your screen.

Example interaction:

Hello, how are you today?


I'm doing well, thanks for asking. How about you?
I'm doing great! I just wanted to chat and catch up.
That's wonderful to hear! I'm always happy to chat.

Manage Incoming talk Requests

When another user start a talk session with you, you will receive a notification on your terminal. The
notification will look something like this:

Message from Talk_Daemon@GFC at 14:23 ...


talk: connection requested by GFC
talk: respond with: talk GFC

To accept the incoming request, you can simply run the following command:

$talk GFC

This will establish the talk session, and you can start communicating with the other user.

If you don't want to accept the incoming request, you can simply ignore it. You can also use
the mesg command to manage your availability for incoming talk requests:

$mesg n

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


27
4) wall command:
The wall command short for “write to all” is used to send messages to all users currently logged
into the system. This command is particularly useful for system administrators who need to notify users
about system maintenance shutdowns or other critical events. The messages sent using wall are displayed on
the terminals of all logged in users ensuring that the information reaches everyone promptly/fast.

Syntax:

$wall [options] [message | file]

Option Description
-n Suppresses the banner that is displayed before the message.
-t timeout Sets a timeout for the message. The message will only be displayed for a
specified number of seconds.
-g group Sends the message only to users in the specified group.
-v Displays version information and exits.
-h Displays help information.

Example 1: broadcast a simple message to all logged in users.

$wall "The system will undergo maintenance at 3 PM."

Example 2: Broadcast Message from File to all logged in users.

$ wall /path/to/message.txt

Example 3: The -t option allows you to set a timeout for the message

$ wall -t 30 "The system will reboot in 30 seconds."

Example 4: By default, the wall command displays a header before the message. You can suppress this
header using the -n option.

$ wall -n "The system will be down for maintenance."

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


28

5) mail command:
The mail command is a utility that enables users to send and receive emails via the command line.
Linux has an inbuilt Mail User Agent program called mailx.
The mailx command is available from a variety of different packages:
 bsd-mailx
 heirloom-mailx
 mailutils

Installing mailx:

1] For Ubuntu/Debian:

sudo apt-get install bsd-mailx

2] Forfedore/centos:

sudo yum install mailx

Syntax:

$mail [option] Mail-address(s)

Options-

Option Description
-s Specify the subject of the mail
-c Send carbon copies of the mail to the list of users.
-b Send blind carbon copies of the mail to the list of users.
-v Verbose mode. Delivery details are displayed on the terminal.
-h Displays help information.

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


29
Example 1: To send a simple email, use the “-s” flag to set the subject in quotes which is followed by the
email of the receiver. After this, mailx waits for the content of the email. To enter new lines, keep hitting
enter. After the content is written, press Ctrl+D & EOT will be displayed by mailx

$ mail -s "A mail sent using mailx" [email protected]


Hey person,
Hope you're fine these days
Thanks
EOT

Example 2: Taking the message from a file

$ mail -s "A mail sent using mailx" [email protected] <


/path/to/file

Example 3: Sending same Mail to Multiple Recipients.

$ mail - s "A mail sent using mailx" [email protected], [email protected] <


/path/to/file

Example 4: Adding CC we use the “-c” option & for BCC we use the “-b” option which is followed by
the email addresses.

$ mail - s "A mail sent using mailx" [email protected] -c [email protected] -b


[email protected] >

/path/to/file

Example 5: Adding attachments are a vital part of email communication. We can attach documents,
images, text files, etc. by using the “-a” option followed by the path of the file that we want to attach.
$ mail - s "A mail sent using mailx" [email protected] -a Attachment.txt

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


30
 Text Editors:
For Linux users, text editors are essential tools that play a crucial role in various tasks, from coding
and writing to system administration and configuration management. Linux offers a wide range of text
editors.

There are two types of text editors:


1] Vi Editor.
2] Vim Editor.

1] Vi Editor:
The Vi is default editor that comes with the Linux/UNIX operating system is called Vi (visual editor).
Vi written by Bill Joy when he was a student at university of California.
Vi the first full screen editor. It allowed the user to view & edit the entire document at the same time. It
creating & editing files.
Vi is visual editor used to enter and edit text files containing data or documents or programs. It displays
the contents of files on the screen and allows the user to add, insert, delete or change parts of the text.

Syntax:

$vi <file-name>

Example: Create file file.txt

$vi file.txt

 Modes of operation:

The vi editor has three modes.


1] Command mode.
2] Input mode.
3] Exit Mode.

1] Command mode:
This mode enables you to perform administrative tasks such as saving the files, executing the
commands, moving the cursor, cutting and pasting the lines or words, as well as finding and replacing. In
this mode, whatever you type is interpreted as a command.

Command mode following:


1. Deletion

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


31
2. Navigation
3. Pattern Search
4. Joining Lines
5. Copy, cut and paste.

1)Deletion: If you want to delete a character, move the cursor to that character and press ' x ' the character
will disappear and the line will readjust to the change. To erase three characters in a row, press ' x ' three
times or press ‘3x’. To delete line in file that time user can use dd command.

Commands Action
x Delete the current character
X Delete the character before the cursor
r Replace the current character
dd Delete the current line
D Delete the current line from current character to the end of the line

2) Navigation: In navigation command mode move the cursor by one position to another position.

Commands Action
j To move down
k To move up
h To move left
l To move right
G Will direct you at the last line of the file
nG over cursor to specific line (5G move cursor to line 5)
M Move cursor to middle line
| (pipe ) Moves to beginning of line
b Moves backward to beginning of word.
e Moves forward to end of word.
w Moves forward to begin of word.
$ Moves the cursor to the end of the current line.

3) Pattern Search: The file containing a string and if you want to search string to use ' / ' forward slash to
pattern search e.g /linux-word.

Commands Action
/string Forward search for given string
?string Backward search for given string
/^string Forward search string at beginning of a line
/string$ Forward search string at end of a line
n Go to next occurrence of searched string

4) Joining Lines:

Commands Action
J Join two lines
yyp Repeat the current line
ddp Swap two lines

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


32
5) Commands to Lines copy, cut, and paste:

Commands Action
yy (yank yank) copy a line
p Paste after the current line
P Paste before the current line

2] Input mode:
This mode permits insertion of new text, editing of existing text or replacement of existing text. Each
of these operations can be performed only after changing over from the command mode to insertion mode.

The Esc key will take you to the command mode from insert mode.

Command Action
i Start typing before the current character
I Start typing at the start of current line
a Start typing after the current character
A Start typing at the end of current line
o Start typing on a new line after the current line
O Start typing on a new line before the current line
r Replace single character under cursor.
R Replace text from cursor to right.
S Replace entire line.

3] Exit Mode:
User edit a file using Vi editor that time you need to save your changeable work that time use
following command to save and exit.

Commands Action
:wq Save and quit
:w Save file and user remaining in that file
:w fname Save as fname
ZZ Save and quit
:q! Quit without save
:w! Save (and write to non-writable file)

2] Vim Editor:
The Vim stands for "Vi Improved", Extended and Newer version of Vi Editor. The Vim is a free &
open-source text editor for Linux that's commonly used for programming, system administration, and
working with markup languages. It's an enhanced version of the vi editor, and is often used in a command-
line interface (CLI).

Features of Vim:

 Plugins: Vim supports plugins and scripting languages like Python and Perl

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


33
 Compression: Vim supports compression functions like tar and zip
 Network transfer: Vim supports network transfer protocols like SSH, FTP, and HTTP
 Autocomplete: Vim has an autocomplete feature
 Comparison mode: Vim has a comparison mode similar to the diff utility
 Vim allows screen to be split for editing multiple files.
 Vim includes multilevel undo and redo features

Advantages of Vim Editor:

1. Lightweight & Fast: Runs in a terminal, making it fast and efficient even on low-resource systems.
2. Highly Customizable: You can tweak everything using the .vimrc file and install plugins to enhance
functionality.
3. Keyboard-Centric Workflow: No need for a mouse everything can be done with powerful
keyboard shortcuts, improving efficiency.
4. Modes for Efficient Editing: Different modes (Normal, Insert, Visual, Command) allow faster
navigation and editing compared to traditional text editors.
5. Works Everywhere: Available on almost every Unix-based system, Windows, and macOS.
6. Extensive Plugin Support: Plugins can add features like auto-completion, syntax highlighting, and
Git integration.
7. Great for Remote Work (SSH): Ideal for editing files on remote servers via SSH since it runs
directly in the terminal.
8. Powerful Search & Replace: Advanced search and replace using regular expressions
(:%s/old/new/g) makes bulk editing easy.
9. Undo Tree & Recovery Features: Multiple undos and persistent undo history help prevent
mistakes.
10. Free & Open Source: Vim is completely free and open-source, supported by a strong community.

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


34
 Archive and File compression commands:

Archiving:
In Linux, "Archive" means combining multiple files into a single package called an archive. To
archive file to uses the "tar" command in Linux.

1] tar command:
The tar command in Linux is a powerful tool used for archiving and managing files and directories.
It stands for "Tape Archive" and was originally designed to work with tape drives.
The tar combines multiple files and directories into a single archive file or extract archive file.
Preserves the directory structure of the original files. The tar is useful for backing up data, transferring large
sets of files, and maintaining organization. In tar command .tar extension is used for file/directory archive.

Syntax:

$ tar [Options ] <File-name.tar> < files-or-directories>

Options Description
-c Creates an archive by bundling files and directories together.
-x Extracts files and directories from an existing archive.
-f Specifies the filename of the archive to be created or extracted.
-t Displays or lists the files and directories contained within an archive.
-u Archives and adds new files or directories to an existing archive.
-v Displays verbose information
-A Concatenates multiple archive files into a single archive.
-z Uses gzip compression when creating a tar file, resulting in a compressed archive with the
‘.tar.gz’ extension.
-W Verifies the integrity of an archive file, ensuring its contents are not corrupted.
-r Appends files at end of archive.

Example 1: Creating an uncompressed tar Archive using option –cvf. This command creates a tar file
called file.tar which is the Archive of all .txt files in the current directory.
$ tar -cvf file.tar *.txt

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


35
Example 2: Extracting files from Archive using option -xvf
$ tar -xvf file.tar *.txt

Example 3: gzip compression on the tar Archive, using option –z. This command creates a tar file called
file.tar.gz which is the Archive of .txt files.
$ tar -czvf file.tar.gz *.txt

Example 4: Extracting a gzip tar Archive *.tar.gz using option –xvzf. This command extracts files from tar
archived file.tar.gz files.
$tar -xzvf file.tar.gz

Compression:
The "file compression" refers to reducing the size of a file by removing redundant data patterns,
allowing you to store more data in less space. To use file compression “gzip” and “zip” to compress data
or “unzip” to extract compress data.

The "gzip" is a command used to compress single files, creating a compressed file with a ".gz" extension.

The "zip" is a more versatile tool that can compress multiple files into a single archive with a ".zip"
extension, allowing you to package and compress files together.

1] zip command:
The zip command in Linux is a utility that compresses files and directories into a single ZIP file
file. It's a useful tool for managing files, especially large amounts of data.

Syntax:

$ zip [Options] <File-name.zip> < files-or-directories>

Options Description
-d Remove files from the archive.
-u Update files in the archive
-m Move files into the archive
-r Recursively zip a directory
-v Verbose mode

Example 1: To compress all files that have the .txt file extension.
$ zip File-Com.zip *.txt

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


36

2] unzip command:
The unzip command extract files from a ZIP file. The default behaviour (with no options) is to
extract into the current directory. All files from the specified ZIP file.

Syntax:

$ unzip <file-name.zip>

Example 1: To extract file from a file-com.zip using –v option.


$ unzip -v File-Com.zip

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


37
 Other Commands:

1] cal command:
The cal command is a calendar command in Linux which is used to see the calendar of a specific
month or a whole year. By default, entering cal in the terminal shows the calendar of the current month, with
today’s date highlighted. This provides a quick overview of the month at hand.

Syntax:

$ cal [Options ] [ Month ] [ year ]

Options:

Options Description
-y Shows the calendar of the complete current year with the current date highlighted.
-3 Shows calendar of previous, current and next month
-j Shows the calendar of the current month in the Julian calendar format.

Note- ‘cal -j’: Shows the calendar of the current month in the Julian calendar format not in the
default Gregorian calendar format. In Julian calendar format, the date does not reset to 1 after every
month’s end i.e. after 31st Jan, Feb will start as 32nd Feb, not as 1st Feb. But in the Gregorian calendar
format, the date is reset to 1 after every month’s end i.e after 31st Jan, Feb will start as of 1st Feb.

Example 1: ‘cal’ Shows current month calendar on the terminal with the current date highlighted.
$ cal

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj


38
Example 2: ‘cal -y’: Shows the calendar of the complete current year with the current date highlighted.
$ cal –y

Example 3: ‘cal [month] [year]’: Shows calendar of selected month and year
$ cal 04 1996

2] date command:
The date command is used to display the system date and time. date command is also used to set
date and time of the system. By default the date command displays the date in the time zone on which
unix/linux operating system is configured. You must be the super-user (root) to change the date and time.
Syntax:

$ date [Option] [+Format]

Options:

Options Description
-u To display the current time in GMT (Greenwich Mean Time) or UTC
(Coordinated Universal Time).

Example 1: Shows current date and time.


$ date

Example 2: To display the current time in GMT


$ date -u

3] who command:
The who command in Linux displays information about users who are currently logged in to the
system. It can also show the date and time of login, the terminal the user is using, and the host name of the
machine they are logged in from.

Syntax:

$ who

Example 1: Shows all list of users who are currently logged in to the system.
$ who

Mr. Yogesh D. Pakhare, M. Sc[CS] College - GFCCT, Akluj

You might also like