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

Unix Commands

The ls command lists directory contents and files. It has many options to customize the output like -l for a long listing, -a to show hidden files, and -R to list recursively. The man command displays manuals for commands, which include descriptions, syntax, options, and examples. The cd command changes the current working directory, for example to navigate into subdirectories. The pwd command prints the current working directory. The mkdir command creates new directories while the rmdir command removes empty directories.

Uploaded by

Anant More
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
143 views

Unix Commands

The ls command lists directory contents and files. It has many options to customize the output like -l for a long listing, -a to show hidden files, and -R to list recursively. The man command displays manuals for commands, which include descriptions, syntax, options, and examples. The cd command changes the current working directory, for example to navigate into subdirectories. The pwd command prints the current working directory. The mkdir command creates new directories while the rmdir command removes empty directories.

Uploaded by

Anant More
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 72

1.

Ls command

 ls is a Linux shell command that lists directory contents of files and
directories

ls syntax:
$ ls [options] [file|dir]

ls command options
ls command main options:
option Description

ls -a list all files including hidden file starting with '.'

ls --color colored list [=always/never/auto]

ls -d list directories - with ' */'

ls -F add one char of */=>@| to entries

ls -i list file's inode index number

ls -l list with long format - show permissions

ls -la list long format including hidden files

ls -lh list long format with readable file size

ls -ls list with long format with file size

ls -r list in reverse order

ls -R list recursively directory tree

ls -s list file size

ls -S sort by file size

ls -t sort by time & date

ls -X sort by extension name

a. Display All Information About Files/Directories Using ls -l


$ ls -l : To show long listing information about the file/directory.

-rw-rw-r– 1 maverick maverick 1176 Feb 16 00:19 1.c


1st Character – File Type: First character specifies the type of the file.
In the example above the hyphen (-) in the 1st character indicates that this is a
normal file. Following are the possible file type options in the 1st character of
the ls -l output.
Field Explanation
 – normal file
 d : directory
 s : socket file
 l : link file
 Field 1 – File Permissions: Next 9 character specifies the files
permission. The every 3 characters specifies read, write, execute
permissions for user(root), group and others respectively in order. Taking
above example, -rw-rw-r– indicates read-write permission for user(root) ,
read permission for group, and no permission for others respectively. If all
three permissions are given to user(root), group and others, the format looks
like -rwxrwxrwx
 Field 2 – Number of links: Second field specifies the number of links for
that file. In this example, 1 indicates only one link to this file.
 Field 3 – Owner: Third field specifies owner of the file. In this example,
this file is owned by username ‘maverick’.
 Field 4 – Group: Fourth field specifies the group of the file. In this
example, this file belongs to ”maverick’ group.
 Field 5 – Size: Fifth field specifies the size of file in bytes. In this
example, ‘1176’ indicates the file size in bytes.
 Field 6 – Last modified date and time: Sixth field specifies the date and
time of the last modification of the file. In this example, ‘Feb 16 00:19’
specifies the last modification time of the file.
 Field 7 – File name: The last field is the name of the file. In this example,
the file name is 1.c.

b. Display Hidden Files Using ls -a (or) ls -A

$ ls -a : To show all the hidden files in the directory, use ‘-a option’. Hidden files
in Unix starts with ‘.’ in its file name.It will show all the files including the ‘.’
(current directory) and ‘..’ (parent directory).

c. Display Files Recursively Using ls -R


$ ls /etc/apt

$ ls -R /etc/apt : To show all the files recursively. When you do this from /, it
shows all the unhidden files in the whole file system recursively.
2. man command
 man command in Linux is used to display the user manual of any
command that we can run on the terminal. It provides a detailed
view of the command which includes NAME, SYNOPSIS, DESCRIPTION,
OPTIONS, EXIT STATUS, RETURN VALUES, ERRORS, FILES, VERSIONS,
EXAMPLES, AUTHORS.
 Every manual is divided into the following sections:
 Executable programs or shell commands
 System calls (functions provided by the kernel)
 Library calls (functions within program libraries
 Games
 Special files (usually found in /dev)
 File formats and conventions eg /etc/passwd
 Miscellaneous (including macro packages and conventions),
e.g. groff(7)
 System administration commands (usually only for root)
 Kernel routines [Non standard]

Syntax :

$ man [COMMAND NAME]

Example:
$ man printf
Output:
In this example, manual pages of the command ‘printf‘ are simply returned.

3. cd command
cd command in linux known as change directory command. It is used to
change current working directory.
Syntax:
$ cd [directory]

To move inside a subdirectory : to move inside a subdirectory in linux we use


$ cd [directory_name]
In the above example, we have checked number of directories in our home
directory and moved inside the Documents directory by using cd Documents
command.

Different functionalities of cd command :


 cd /: this command is used to change directory to the root directory, The
root directory is the first directory in your filesystem hierarchy.
$ cd /

Above, / represents the root directory.


 cd dir_1/dir_2/dir_3: This command is used to move inside a directory
from a directory
$ cd dir_1/dir_2/dir_3
In above example, we have the document directory and inside the document
directory we have a directory named geeksforgeeks and inside that directory
we have example directory. To navigate example directory we have used
command cd Documents/geeksforgeeks/example.
 cd ~ : this command is used to change directory to the home directory.
$ cd ~

or
$ cd
cd : this commad also work same as cd ~ command.

 cd .. : this command is used to move to the parent directory of current


directory, or the directory one level up from the current directory. “..”
represents parent directory.
$ cd ..
 cd “dir name”: This command is used to navigate to a directory with
white spaces.Instead of using double quotes we can use single quotes then
also this command will work.
$ cd "dir name"

In above example, we have navigated the My songs directory by using cd


“My songs” command.
or
$ cd dir\ name :
this command work same as cd “dir name” command.
4. pwd command

 pwd stands for Print Working Directory. It prints the path of the working


directory, starting from the root.
pwd is shell built-in command(pwd) or an actual binary(/bin/pwd).
$PWD is an environment variable which stores the path of the current
directory.
This command has two flags.
pwd -L: Prints the symbolic path.
pwd -P: Prints the actual path.
A)Built-in pwd (pwd):

In the given example the directory /home/shital/logs/ is a symbolic link for a


target directory /var/logs/
B)Binary pwd (/bin/pwd):

The default behavior of Built-in pwd is same as pwd -L.


And the default behavior of /bin/pwd is same as pwd -P.
The $PWD variable value is same as pwd -L.
5. mkdir command

mkdir command in Linux allows the user to create directories (also referred to


as folders in some operating systems ). This command can create multiple
directories at once as well as set the permissions for the directories. It is
important to note that the user executing this command must have enough
permissions to create a directory in the parent directory, or he/she may recieve
a ‘permission denied’ error.
Syntax:
mkdir [options...] [directories ...]
 --version: Itdisplays the version number, some information regarding the
license and exits.
Syntax:
mkdir --version
Output:

 --help: It displays the help related information and exits.


Syntax:
 mkdir --help
Output:

 -v or --verbose: It displays a message for every directory created.


Syntax:

mkdir -v [directories]
Output:

 -p:
A flag which enables the command to create parent directories as
necessary. If the directories exist, no error is specified.
Syntax:
mkdir -p [directories]
Suppose you execute the following command –
mkdir -p first/second/third
If the first and second directories do not exist, due to the -p option, mkdir
will create these directories for us. If we do not specify the -p option, and
request the creation of directories, where parent directory doesn’t exist, we
will get the following output –

If we specify the -p option, the directories will be created, and no error will be


reported. Following is the output of one such execution. We’ve also provided
the -v option, so that we can see it in action.
Output:

 -m:This option is used to set the file modes, i.e. permissions, etc. for the
created directories. The syntax of the mode is the same as
the chmod command.
Syntax:
mkdir -m a=rwx [directories]
The above syntax specifies that the directories created give access to all the
users to read from, write to and execute the contents of the created
directories. You can use ‘a=r’ to only allow all the users to read from the
directories and so on.
Output:

6. rmdir command

rmdir command is used remove empty directories from the filesystem in Linux.


The rmdir command removes each and every directory specified in the
command line only if these directories are empty. So if the specified directory
has some directories or files in it then this cannot be removed
by rmdir command.
Syntax:
rmdir [-p] [-v | –verbose] [–ignore-fail-on-non-empty] directories …
Options:
 –help: It will print the general syntax of the command along with the
various options that can be used with the rmdir command as well as give a
brief description about each option.

 rmdir -p: In this option each of the directory argument is treated as a


pathname of which all components will be removed, if they are already
empty, starting from the last component.
 rmdir -v, –verbose: This option displays verbose information for every
directory being processed.
 rmdir –ignore-fail-on-non-empty: This option do not report a failure
which occurs solely because a directory is non-empty. Normally, when rmdir
is being instructed to remove a non-empty directory, it simply reports an
error. This option consists of all those error messages.
 rmdir –version: This option is used to display the version information
and exit.

Example 1: This will first remove the child directory and then remove the parent
directory.

rmdir -p mydir/mydir1
Example 2: Remove the directories mydir1, mydir2, and mydir3, if they are
empty. If any of these directories are not empty, then an error message will be
printed for that directory, and the other directories will be removed.
rmdir mydir1 mydir2 mydir3

Example 3: Remove the directory  mydir/mydir1 if it is empty. Then, remove


directory mydir, if it is empty after mydir/mydir1 was removed.
rmdir mydir/mydir1 mydir

7. wc command

wc stands for word count. As the name implies, it is mainly used for counting
purpose.
 It is used to find out number of lines, word count, byte and characters
count in the files specified in the file arguments.
 By default it displays four-columnar output.
 First column shows number of lines present in a file specified, second
column shows number of words present in the file, third column shows
number of characters present in file and fourth column itself is the file name
which are given as argument.
Syntax:
wc [OPTION]... [FILE]...
Let us consider two files having name state.txt and capital.txt containing 5
names of the Indian states and capitals respectively.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
$ cat capital.txt
Hyderabad
Itanagar
Dispur
Patna
Raipur
Passing only one file name in the argument.
$ wc state.txt
5 7 63 state.txt
OR
$ wc capital.txt
5 5 45 capital.txt
Passing more than one file name in the argument.

$ wc state.txt capital.txt
5 7 63 state.txt
5 5 45 capital.txt
10 12 108 total
Note : When more than file name is specified in argument then command will
display four-columnar output for all individual files plus one extra row displaying
total number of lines, words and characters of all the files specified in argument,
followed by keyword total.
Options:
1. -l: This option prints the number of lines present in a file. With this option wc
command displays two-columnar output, 1st column shows number of lines
present in a file and 2nd itself represent the file name.
With one file name
$ wc -l state.txt
5 state.txt

With more than one file name


$ wc -l state.txt capital.txt
5 state.txt
5 capital.txt
10 total
2. -w: This option prints the number of words present in a file. With this option
wc command displays two-columnar output, 1st column shows number of words
present in a file and 2nd is the file name.
With one file name
$ wc -w state.txt
7 state.txt
With more than one file name
$ wc -w state.txt capital.txt
7 state.txt
5 capital.txt
12 total
3. -c: This option displays count of bytes present in a file. With this option it
display two-columnar output, 1st column shows number of bytes present in a
file and 2nd is the file name.
With one file name
$ wc -c state.txt
63 state.txt

With more than one file name


$ wc -c state.txt capital.txt
63 state.txt
45 capital.txt
108 total
4. -m: Using -m option ‘wc’ command displays count of characters from a file.
With one file name
$ wc -m state.txt
63 state.txt

With more than one file name


$ wc -m state.txt capital.txt
63 state.txt
45 capital.txt
108 total
5. -L: The ‘wc’ command allow an argument -L, it can be used to print out the
length of longest (number of characters) line in a file. So, we have the longest
character line Arunachal Pradesh in a file state.txt and Hyderabad in the
file capital.txt. But with this option if more than one file name is specified then
the last row i.e. the extra row, doesn’t display total but it display the maximum of
all values displaying in the first column of individual files.
Note: A character is the smallest unit of information that includes space, tab
and newline.
With one file name
$ wc -L state.txt
17 state.txt

With more than one file name


$ wc -L state.txt capital.txt
17 state.txt
10 capital.txt
17 total
6. –version: This option is used to display the version of wc which is currently
running on your system.

$ wc --version
wc (GNU coreutils) 8.26
Packaged by Cygwin (8.26-1)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Paul Rubin and David MacKenzie.


Applications of wc Command
1. To count all files and folders present in directory: As we all
know ls command in unix is used to display all the files and folders present in
the directory, when it is piped with wc command with -l option it display count of
all files and folders present in current directory.
$ ls gfg
a.txt
b.txt
c.txt
d.txt
e.txt
geeksforgeeks
India

$ ls gfg | wc -l
7
2. Display number of word count only of a file: We all know that this can be
done with wc command having -w option, wc -w file_name, but this command
shows two-columnar output one is count of words and other is file name.
$ wc -w state.txt
7 state.txt
So to display 1st column only, pipe(|) output of wc -w command
to cut command with -c option. Or use input redirection(<).
$ wc -w state.txt | cut -c1
7
OR
$ wc -w < state.txt
7

8. kill command
kill command in Linux (located in /bin/kill), is a built-in command which is used
to terminate processes manually. kill command sends a signal to a process
which terminates the process. If the user doesn’t specify any signal which is to
be sent along with kill command then default TERM  signal is sent that
terminates the process.
Options and examples
1. kill -l :To display all the available signals you can use below command
option:
Syntax:
$kill -l

Signals can be specified in three ways:

 By number (e.g. -5)


 With SIG prefix (e.g. -SIGkill)
 Without SIG prefix (e.g. -kill)
Note:
 Negative PID values are used to indicate the process group ID. If you
pass a process group ID then all the process within that group will receive
the signal.
 A PID of -1 is very special as it indicates all the processes except kill and
init, which is the parent process of all processes on the system.
 To display a list of running processes use the command ps and this will
show you running processes with their PID number. To specify which
process should receive the kill signal we need to provide the PID.
Syntax:
$ps

2. kill pid : To show how to use a PID with the kill  command.


Syntax:
$kill pid

3. kill -s : To show how to send signal to processes.


Syntax:
kill {-signal | -s signal} pid
4. kill -L :This command is used to list available signals in a table format.
Syntax:
kill {-l | --list[=signal] | -L | --table}

9. top command
 top command is used to show the Linux processes. It provides a dynamic
real-time view of the running system. Usually, this command shows the
summary information of the system and the list of processes or threads
which are currently managed by the Linux Kernel.
As soon as you will run this command it will open an interactive command
mode where the top half portion will contain the statistics of processes
and resource usage. And Lower half contains a list of the currently
running processes. Pressing q  will simply exit the command mode.
 Top syntax:
top
10.chmod command
In Unix-like operating systems, the chmod command is used to change the
access mode of a file.
The name is an abbreviation of change mode.
Syntax :
chmod [reference][operator][mode] file...
The references are used to distinguish the users to whom the permissions
apply i.e. they are list of letters that specifies whom to give permissions. The
references are represented by one or more of the following letters:
Reference Class Description
u owner file's owner

g group users who are members of


the file's group

o others users who are neither the


file's owner nor members of
the file's group

a all All three of the above, same as ugo


The operator is used to specify how the modes of a file should be adjusted. The
following operators are accepted:
Operator Description
+ Adds the specified modes to the
specified classes

- Removes the specified modes from


the specified classes

= The modes specified are to be made


the exact modes for the specified
classes
Note : Putting blank space(s) around operator would make the command fail.

The modes indicate which permissions are to be granted or removed from the
specified classes. There are three basic modes which correspond to the basic
permissions:
r Permission to read the file.
w Permission to write (or delete) the file.
x Permission to execute the file, or, in
the case of a directory, search it.
Types of permissions which we will be changing using chmod command :
In linux terminal, to see all the permissions to different files, type ls -l command
which lists the files in the working directory in long format. The figure below
shows an example to use ls -l and its output :
Let us take a look at above figure. To make things easy to understand some
columns and rows are eliminated and extra spaces are added to the
permissions column to make it easier to read as shown below:
- rw- rw- r-- mik mik assgn1_client.c
- rw- rw- r-- mik mik assgn1_server.c
d rwx rwx r-x mik mik EXAM
- rw- rw- r-- mik mik raw.c
- rwx r-x r-x mik mik header.sh
... so on...
 The very first column represents the type of the file i.e. is it a normal file
or a
directory where d represents a directory and – represents a normal file.
 The first set three letters after the file type tell what the Owner of the file,
have permissions to do. For example: In assgn1_client.c, has owner’s
permission as rw-, which means the owner mik can only read(r) and write(w)
the file but cannot execute(x).
 Note: The 3rd and 4th columns represents the name of the owner of the
file and the group to which the owner belongs respectively.
 The next three letters after the user’s permission are the group’s
permissions.
For example: header.sh has group permissions as r-x, which means Other
people in the mik group can not write(w) the header.sh script but can only
read(r) or execute(x) it.
 Note that when a directory has the x set, this takes the special meaning
of “permitted to search this directory”.
 The last three letters in the permissions column tell us what the “others”
may do. The general practice is to protect the files from external access so
that others can’t write any files or directories. They may read(r) or execute(x)
it. For example: The assgn1_client.c has others permission as r- – which
means it can only be read by other(external) access but cannot be written or
executed by them.
Now, let us see how chmod command can be used to change the access mode
of a file.
Example 1 :
Let’s change the assgn1_client.c permission so that the owner cannot write(w)
in the file but can only read it.
BEFORE: -rw-rw-r-- mik mik assgn1_client.c

COMMAND: chmod u=r assgn1_client.c

AFTER: -r--rw-r-- mik mik assgn1_client.c


Before :
After :

Example 2 :
Let’s restrict the permission such that the user cannot search the directory
EXAM.
BEFORE: drwxrwxr-x mik mik EXAM

COMMAND: chmod u=rw EXAM

AFTER: drw-rwxr-x mik mik EXAM


After applying the chmod u=rw EXAM command, the user (owner) cannot
change the directory. If the user tries to change the directory, then it shows the
message “Permission denied” as shown in the figure below :

3. chmod o+rwx hello.c


4. chmod 741 hello.c
111, 100, 001
Rwxr----x

11. head & tail command


 It is the complementary of Tail command. The head command, as
the name implies, print the top N number of data of the given input.
By default, it prints the first 10 lines of the specified files. If more
than one file name is provided then data from each file is preceded
by its file name. 

Syntax: 
 
head [OPTION]... [FILE]...
Let us consider two files having name state.txt and capital.txt contains all the
names of the Indian states and capitals respectively. 
 
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Jharkhand
Karnataka
Kerala
Madhya Pradesh
Maharashtra
Manipur
Meghalaya
Mizoram
Nagaland
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
Without any option, it displays only the first 10 lines of the file specified. 
Example: 
 
$ head state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Options 

1. -n num: Prints the first ‘num’ lines instead of first 10 lines. num is mandatory


to be specified in command otherwise it displays an error. 
 
$ head -n 5 state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
2. -c num: Prints the first ‘num’ bytes from the file specified. Newline count as a
single character, so if head prints out a newline, it will count it as a byte. num is
mandatory to be specified in command otherwise displays an error. 
 
$ head -c 6 state.txt
Andhra
3. -q: It is used if more than 1 file is given. Because of this command, data from
each file is not precedes by its file name. 
 
Without using -q option
==> state.txt capital.txt <==
Hyderabad
Itanagar
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar

With using -q option


$ head -q state.txt capital.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Hyderabad
Itanagar
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
4. -v: By using this option, data from the specified file is always preceded by its
file name. 
 
$ head -v state.txt
==> state.txt <==
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
 
Applications of head Command
 
1. Print line between M and N lines(M>N): For this purpose, we use the
head, tail, and pipeline(|) commands. The command is: head -M file_name |
tail +N since the head command takes first M lines and from M lines tail
command cuts lines starting from +N till the end, we can also use head -M
file_name | tail +(M-N+1) command since the head command takes first M
lines and from M lines tail command cuts (M-N+1) lines starting from the
end. Let say from the state.txt file we have to print lines between 10 and 20. 
 
$ head -n 20 state.txt | tail -10
Jharkhand
Karnataka
Kerala
Madhya Pradesh
Maharashtra
Manipur
Meghalaya
Mizoram
Nagaland
Odisha
1. How to use the head with pipeline(|): The head command can be piped
with other commands. In the following example, the output of the ls
command is piped to head to show only the three most recently modified
files or folders. 
 
Display all recently modified or recently used files.
$ ls -t
e.txt
d.txt
c.txt
b.txt
a.txt
Cut three most recently used file.
$ ls -t | head -n 3
e.txt
d.txt
c.txt
1. It can also be piped with one or more filters for additional processing. For
example, the sort filter could be used to sort the three most recently used
files or folders in the alphabetic order. 
 
$ ls -t | head -n 3 | sort
c.txt
d.txt
e.txt

Tail command:
It is the complementary of head command.The tail command, as the name
implies, print the last N number of data of the given input. By default it prints the
last 10 lines of the specified files. If more than one file name is provided then
data from each file is precedes by its file name.
Syntax:
tail [OPTION]... [FILE]...
Let us consider two files having name state.txt and capital.txt contains all the
names of the Indian states and capitals respectively.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Jharkhand
Karnataka
Kerala
Madhya Pradesh
Maharashtra
Manipur
Meghalaya
Mizoram
Nagaland
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
Without any option it display only the last 10 lines of the file specified.
Example:
$ tail state.txt
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
Options:
1. -n num: Prints the last ‘num’ lines instead of last 10 lines. num is mandatory
to be specified in command otherwise it displays an error. This command can
also be written as without symbolizing ‘n’ character but ‘-‘ sign is mandatory.
$ tail -n 3 state.txt
Uttar Pradesh
Uttarakhand
West Bengal
OR
$ tail -3 state.txt
Uttar Pradesh
Uttarakhand
West Bengal
Tail command also comes with an ‘+’ option which is not present in the head
command. With this option tail command prints the data starting from specified
line number of the file instead of end. For command: tail +n file_name, data will
start printing from line number ‘n’ till the end of the file specified.
$ tail +25 state.txt
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
2. -c num: Prints the last ‘num’ bytes from the file specified. Newline count as a
single character, so if tail prints out a newline, it will count it as a byte. In this
option it is mandatory to write -c followed by positive or negative num depends
upon the requirement. By +num, it display all the data after skipping num bytes
from starting of the specified file and by -num, it display the last num bytes
from the file specified.
Note: Without positive or negative sign before num, command will display the
last num bytes from the file specified.
With negative num
$ tail -c -6 state.txt
Bengal
OR
$ tail -c 6 state.txt
Bengal

With positive num


$ tail -c +263 state.txt
Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
3. -q: It is used if more than 1 file is given. Because of this command, data from
each file is not precedes by its file name.
Without using -q option
$ tail state.txt capital.txt
state.txt
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
capital.txt
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
Ranchi

With using -q option


$ tail -q state.txt capital.txt
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West BengalDispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
Ranchi
Bengaluru
4. -f: This option is mainly used by system administration to monitor the growth
of the log files written by many Unix program as they are running. This option
shows the last ten lines of a file and will update when new lines are added. As
new lines are written to the log, the console will update with the new lines. The
prompt doesn’t return even after work is over so, we have to use the interrupt
key to abort this command. In general, the applications writes error messages
to log files. You can use the -f option to check for the error messages as and
when they appear in the log file.
$ tail -f logfile
5. -v: By using this option, data from the specified file is always preceded by its
file name.
$ tail -v state.txt
==> state.txt <==
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
6. –version: This option is used to display the version of tail which is currently
running on your system.
$ tail --version
tail (GNU coreutils) 8.26
Packaged by Cygwin (8.26-1)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Paul Rubin, David MacKenzie, Ian Lance Taylor,


and Jim Meyering.

Applications of tail Command


1. How to use tail with pipes(|): The tail command can be piped with many
other commands of the unix. In the following example output of the tail
command is given as input to the sort command with -r option to sort the last 7
state names coming from file state.txt in the reverse order.
$ tail -n 7 state.txt
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal

$ tail -n 7 state.txt | sort -r


West Bengal
Uttarakhand
Uttar Pradesh
Tripura
Telangana
Tamil Nadu
Sikkim
It can also be piped with one or more filters for additional processing. Like in the
following example, we are using cat, head and tail command and whose output
is stored in the file name list.txt using directive(>).
$ cat state.txt | head -n 20 | tail -n 5 > list.txt

$ cat list.txt
Manipur
Meghalaya
Mizoram
Nagaland
Odisha
What is happening in this command let’s try to explore it. First cat command
gives all the data present in the file state.txt and after that pipe transfers all the
output coming from cat command to the head command. Head command gives
all the data from start(line number 1) to the line number 20 and pipe transfer all
the output coming from head command to tail command. Now, tail command
gives last 5 lines of the data and the output goes to the file name list.txt via
directive operator.

12.copy command
cp stands for copy. This command is used to copy files or group of files or
directory. It creates an exact image of a file on a disk with different file
name. cp  command require at least two filenames in its arguments.
Syntax:
cp [OPTION] Source Destination
cp [OPTION] Source Directory
cp [OPTION] Source-1 Source-2 Source-3 Source-n Directory

First and second syntax is used to copy Source file to Destination


file or Directory.
Third syntax is used to copy multiple Sources(files) to Directory.
cp command works on three principal modes of operation and these
operations depend upon number and type of arguments passed in cp
command :
1. Two file names : If the command contains two file names, then it copy
the contents of 1st file to the 2nd file. If the 2nd file doesn’t exist, then first it
creates one and content is copied to it. But if it existed then it is simply
overwritten without any warning. So be careful when you choose destination
file name.
2. cp Src_file Dest_file
Suppose there is a directory named geeksforgeeks having a text file a.txt.
Example:
$ ls
a.txt

$ cp a.txt b.txt

$ ls
a.txt b.txt
3. One or more arguments : If the command has one or more arguments,
specifying file names and following those arguments, an argument specifying
directory name then this command copies each source file to the destination
directory with the same name, created if not existed but if already existed
then it will be overwritten, so be careful !!.
4. cp Src_file1 Src_file2 Src_file3 Dest_directory
Suppose there is a directory named geeksforgeeks having a text file a.txt,
b.txt and a directory name new in which we are going to copy all files.
Example:

$ ls
a.txt b.txt new

Initially new is empty


$ ls new

$ cp a.txt b.txt new

$ ls new
a.txt b.txt
Note: For this case last argument must be a directory name. For the above
command to work, Dest_directory must exist because cp command won’t
create it.
5. Two directory names : If the command contains two directory
names, cp copies all files of the source directory to the destination directory,
creating any files or directories needed. This mode of operation requires an
additional option, typically R, to indicate the recursive copying of directories.
6. cp -R Src_directory Dest_directory
In the above command, cp behavior depend upon whether Dest_directory is
exist or not. If the Dest_directory  doesn’t exist, cp creates it and copies
content of Src_directory recursively as it is. But if Dest_directory exists then
copy of Src_directory becomes sub-directory under Dest_directory.
Options:
There are many options of cp command, here we will discuss some of the
useful options:
Suppose a directory named geeksforgeeks contains two files having some
content named as a.txt and b.txt. This scenario is useful in understanding the
following options.
$ ls geeksforgeeks
a.txt b.txt

$ cat a.txt
GFG
$ cat b.txt
GeeksforGeeks
1. -i(interactive): i stands for Interactive copying. With this option system first
warns the user before overwriting the destination file. cp prompts for a
response, if you press y then it overwrites the file and with any other option
leave it uncopied.
$ cp -i a.txt b.txt
cp: overwrite 'b.txt'? y

$ cat b.txt
GFG
2. -b(backup): With this option cp command creates the backup of the
destination file in the same folder with the different name and in different format.
$ ls
a.txt b.txt

$ cp -b a.txt b.txt

$ ls
a.txt b.txt b.txt~
3. -f(force): If the system is unable to open destination file for writing operation
because the user doesn’t have writing permission for this file then by using -
f option with cp command, destination file is deleted first and then copying of
content is done from source to destination file.
$ ls -l b.txt
-r-xr-xr-x+ 1 User User 3 Nov 24 08:45 b.txt

User, group and others doesn't have writing permission.

Without -f option, command not executed


$ cp a.txt b.txt
cp: cannot create regular file 'b.txt': Permission denied

With -f option, command executed successfully


$ cp -f a.txt b.txt
4. -r or -R: Copying directory structure. With this option cp command shows its
recursive behavior by copying the entire directory structure recursively.
Suppose we want to copy geeksforgeeks directory containing many files,
directories into gfg directory(not exist).
$ ls geeksforgeeks/
a.txt b.txt b.txt~ Folder1 Folder2

Without -r option, error


$ cp geeksforgeeks gfg
cp: -r not specified; omitting directory 'geeksforgeeks'
With -r, execute successfully
$ cp -r geeksforgeeks gfg

$ ls gfg/
a.txt b.txt b.txt~ Folder1 Folder2

5. -p(preserve): With -p option cp preserves the following characteristics of


each source file in the corresponding destination file: the time of the last data
modification and the time of the last access, the ownership (only if it has
permissions to do this), and the file permission-bits.
Note: For the preservation of characteristics you must be the root user of the
system, otherwise characteristics changes.
$ ls -l a.txt
-rwxr-xr-x+ 1 User User 3 Nov 24 08:13 a.txt

$ cp -p a.txt c.txt

$ ls -l c.txt
-rwxr-xr-x+ 1 User User 3 Nov 24 08:13 c.txt
As we can see above both a.txt and c.txt(created by copying) have same
characteristics.
Examples:
Copying using * wildcard: The star wildcard represents anything i.e. all files
and directories. Suppose we have many text document in a directory and wants
to copy it another directory, it takes lots of time if we copy files 1 by 1 or
command becomes too long if specify all these file names as the argument, but
by using * wildcard it becomes simple.
Initially Folder1 is empty
$ ls
a.txt b.txt c.txt d.txt e.txt Folder1

$ cp *.txt Folder1

$ ls Folder1
a.txt b.txt c.txt d.txt e.txt

13.move command
 mv stands for move. mv is used to move one or more files or
directories from one place to another in a file system like UNIX. It
has two distinct functions: 
(i) It renames a file or folder. 
(ii) It moves a group of files to a different directory. 
No additional space is consumed on a disk during renaming. This
command normally works silently means no prompt for
confirmation. 
Syntax: 
mv [Option] source destination
Let us consider 4 files having names a.txt, b.txt, and so on till d.txt. 
To rename the file a.txt to geek.txt(not exist): 
$ ls
a.txt b.txt c.txt d.txt

$ mv a.txt geek.txt

$ ls
b.txt c.txt d.txt geek.txt
If the destination file doesn’t exist, it will be created. In the above
command mv simply replaces the source filename in the directory with
the destination filename(new name). If the destination file exist, then it
will be overwrite and the source file will be deleted. By
default, mv doesn’t prompt for overwriting the existing file, So be
careful !! 
Let’s try to understand with an example,
moving geeks.txt to b.txt(exist): 

$ ls
b.txt c.txt d.txt geek.txt

$ cat geek.txt
India

$ cat b.txt
geeksforgeeks

$ mv geek.txt b.txt

$ ls
b.txt c.txt d.txt

$ cat b.txt
India
Options: 
1. -i (Interactive): Like in cp, the -i option makes the command ask the user
for confirmation before moving a file that would overwrite an existing file,
you have to press y for confirm moving, any other key leaves the file as it is.
This option doesn’t work if the file doesn’t exist, it simply rename it or move
it to new location. 
$ ls
b.txt c.txt d.txt geek.txt

$ cat geek.txt
India

$ cat b.txt
geeksforgeeks

$ mv -i geek.txt b.txt
mv: overwrite 'b.txt'? y

$ ls
b.txt c.txt d.txt

$ cat b.txt
India
2. -f (Force): mv prompts for confirmation overwriting the destination file
if a file is write-protected. The -f option overrides this minor protection
and overwrites the destination file forcefully and deletes the source file. 
$ ls
b.txt c.txt d.txt geek.txt

$ cat b.txt
geeksforgeeks

$ ls -l b.txt
-r--r--r--+ 1 User User 13 Jan 9 13:37 b.txt

$ mv geek.txt b.txt
mv: replace 'b.txt', overriding mode 0444 (r--r--r--)? n

$ ls
b.txt c.txt d.txt geek.txt

$ mv -f geek.txt b.txt

$ ls
b.txt c.txt d.txt

$ cat b.txt
India
3. -n (no-clobber): With -n option, mv prevent an existing file from being
overwritten. 
In the following example the effect is for nothing to happen as a file
would be overwritten. 

$ ls
b.txt c.txt d.txt geek.txt

$ cat b.txt
geeksforgeeks

$ mv -n geek.txt b.txt

$ ls
b.txt c.txt d.txt geek.txt

$ cat b.txt
geeksforgeeks
4. -b(backup): With this option, it is easier to take a backup of an
existing file that will be overwritten as a result of the mv command. This
will create a backup file with the tilde character(~) appended to it. 
$ ls
b.txt c.txt d.txt geek.txt

$ mv -b geek.txt b.txt

$ ls
b.txt b.txt~ c.txt d.txt
5. –version: This option is used to display the version of mv which is
currently running on your system. 
$ mv --version
mv (GNU coreutils) 8.26
Packaged by Cygwin (8.26-2)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute
it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Parker, David MacKenzie, and Jim Meyering.

14.cat command
 Cat(concatenate) command is very frequently used in Linux. It
reads data from the file and gives their content as output. It helps
us to create, view, concatenate files. So let us see some frequently
used cat commands. 
1) To view a single file 
Command: 
 
$cat filename

Output 
 
It will show content of given filename

2) To view multiple files 


Command: 
 
$cat file1 file2

Output 
 

This will show the content of file1 and file2.

3) To view contents of a file preceding with line numbers. 


Command: 
 
$cat -n filename
Output 
 
It will show content with line number
example:-cat-n geeks.txt
1)This is geeks
2)A unique array
4) Create a file 
Command: 
 
$ cat >newfile
Output 
 
Will create and a file named newfile
5) Copy the contents of one file to another file. 
Command: 
 
$cat [filename-whose-contents-is-to-be-copied] > [destination-
filename]

Output 
 
The content will be copied in destination file

6) Cat command can suppress repeated empty lines in output 


Command: 
 
$cat -s geeks.txt

Output 
 
Will suppress repeated empty lines in output

7) Cat command can append the contents of one file to the end of
another file. 
Command: 
 
$cat file1 >> file2

Output 
 
Will append the contents of one file to the end of another file

8) Cat command can display content in reverse order using tac


command. 
Command: 
 
$tac filename

Output 
 
Will display content in reverse order

9) Cat command can highlight the end of line. 


Command: 
 
$cat -E "filename"
Output 
 
Will highlight the end of line

10) If you want to use the -v, -E and -T option together, then instead
of writing -vET in the command, you can just use the -A command
line option. 
Command 
 
$cat -A "filename"

11) Cat command to open dashed files. 


Command: 
 
$cat -- "-dashfile"

Output 
 
Will display the content of -dashfile

12) Cat command if the file has a lot of content and can’t fit in the
terminal. 
Command: 
 
$cat "filename" | more

Output 
 
Will show that much content, which could fit in terminal and
will ask to show more.

12) Cat command to merge the contents of multiple files. 


Command: 
 
$cat "filename1" "filename2" "filename3" > "merged_filename"

Output 
 
Will merge the contents of file in respective order and will
insert that content in "merged_filename".

13) Cat command to display the content of all text files in the
folder. 
Command: 
 
$cat *.txt

Output 
 
Will show the content of all text files present in the folder.
14) Cat command to write in an already existing file. 
Command :
$cat >> geeks.txt
The newly added text.
Output
Will append the text "The newly added text." to the end of the
file.

14.less command

Less command is linux utility which can be used to read contents of text file one
page(one screen) per time. It has faster access because if file is large, it don’t
access complete file, but access it page by page.
For example, if it’s a large file and you are reading it using any text editor, then
the complete file will be loaded to main memory, but less command don’t load
entire file, but load it part by part, which makes it faster.
syntax :
less filename
Note : I’m using dmesg output as input to less command in following examples.
For Example : If you want to read contents of dmesg command, it’s better to
use it with less command

dmesg | less
Output :
[ 0.000000] microcode: microcode updated early to revision 0x21,
date = 2017-11-20
[ 0.000000] random: get_random_bytes called from
start_kernel+0x42/0x504 with crng_init=0
[ 0.000000] Linux version 4.13.0-26-generic (buildd@lgw01-amd64-
031) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5))
#29~16.04.
2-Ubuntu SMP Tue Jan 9 22:00:44 UTC 2018 (Ubuntu 4.13.0-
26.29~16.04.2-generic 4.13.13)
[ 0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-4.13.0-26-
generic.efi.signed root=UUID=993a37f2-7ea9-43a3-b652-5b26bb879797 ro
quiet splash vt.handoff=7
[ 0.000000] KERNEL supported cpus:
[ 0.000000] Intel GenuineIntel
[ 0.000000] AMD AuthenticAMD
[ 0.000000] Centaur CentaurHauls
[ 0.000000] x86/fpu: Supporting XSAVE feature 0x001: 'x87 floating
point registers'
[ 0.000000] x86/fpu: Supporting XSAVE feature 0x002: 'SSE
registers'
[ 0.000000] x86/fpu: Supporting XSAVE feature 0x004: 'AVX
registers'
[ 0.000000] x86/fpu: xstate_offset[2]: 576, xstate_sizes[2]: 256
[ 0.000000] x86/fpu: Enabled xstate features 0x7, context size is
832 bytes, using 'standard' format.
[ 0.000000] e820: BIOS-provided physical RAM map:
[ 0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000006efff]
usable
[ 0.000000] BIOS-e820: [mem 0x000000000006f000-0x000000000006ffff]
reserved
[ 0.000000] BIOS-e820: [mem 0x0000000000070000-0x0000000000087fff]
usable
[ 0.000000] BIOS-e820: [mem 0x0000000000088000-0x00000000000bffff]
reserved
[ 0.000000] BIOS-e820: [mem 0x0000000000100000-0x0000000094d5ffff]
usable
[ 0.000000] BIOS-e820: [mem 0x0000000094d60000-0x0000000095d5ffff]
reserved
[ 0.000000] BIOS-e820: [mem 0x0000000095d60000-0x000000009a36efff]
usable
[ 0.000000] BIOS-e820: [mem 0x000000009a36f000-0x000000009aebefff]
reserved
[ 0.000000] BIOS-e820: [mem 0x000000009aebf000-0x000000009afbefff]
ACPI NVS
[ 0.000000] BIOS-e820: [mem 0x000000009afbf000-0x000000009affefff]
ACPI data
[ 0.000000] BIOS-e820: [mem 0x000000009afff000-0x000000009affffff]
usable
[ 0.000000] BIOS-e820: [mem 0x000000009b000000-0x000000009f9fffff]
reserved
[ 0.000000] BIOS-e820: [mem 0x00000000e0000000-0x00000000efffffff]
reserved
[ 0.000000] BIOS-e820: [mem 0x00000000fe101000-0x00000000fe112fff]
reserved
[ 0.000000] BIOS-e820: [mem 0x00000000feb00000-0x00000000feb0ffff]
reserved
[ 0.000000] BIOS-e820: [mem 0x00000000fec00000-0x00000000fec00fff]
reserved
[ 0.000000] BIOS-e820: [mem 0x00000000fed00000-0x00000000fee00fff]
reserved
[ 0.000000] BIOS-e820: [mem 0x00000000ffc00000-0x00000000ffffffff]
reserved
[ 0.000000] BIOS-e820: [mem 0x0000000100000000-0x000000025f5fffff]
usable
[ 0.000000] NX (Execute Disable) protection: active
[ 0.000000] e820: update [mem 0x93c97018-0x93ca7057] usable ==>
usable
[ 0.000000] e820: update [mem 0x93c97018-0x93ca7057] usable ==>
usable
[ 0.000000] e820: update [mem 0x93c8a018-0x93c96057] usable ==>
usable
[ 0.000000] e820: update [mem 0x93c8a018-0x93c96057] usable ==>
usable
:
mostly used Options :
-E : causes less to automatically exit the first time it reaches end of file.
-f : forces non-regular file to open.
-F : causes less to exit if entire file can be displayed on first screen
-g : highlight the string which was found by last search command
-G : suppresses all highlighting of strings found by search commands
-i : cause searches to ignore case
-n : suppresses line numbers
-p pattern : it tells less to start at the first occurrence of pattern in the file
-s : causes consecutive blank lines to be squeezed into a single blank line
Command Usage with options :
dmesg | less -p "failure"
The above command tells less to start at first occurrence of pattern “failure” in
the file.
Output :
[ 368.748104] wlp2s0: failed to remove key (1, ff:ff:ff:ff:ff:ff)
from hardware (-22)
[ 372.254014] wlp2s0: authenticate with a0:55:4f:27:bd:01
[ 372.257112] wlp2s0: send auth to a0:55:4f:27:bd:01 (try 1/3)
[ 372.261055] wlp2s0: authenticated
[ 372.264307] wlp2s0: associate with a0:55:4f:27:bd:01 (try 1/3)
[ 372.270621] wlp2s0: RX AssocResp from a0:55:4f:27:bd:01
(capab=0x431 status=0 aid=199)
[ 372.272312] wlp2s0: associated
[ 372.357068] wlp2s0: Limiting TX power to 30 (30 - 0) dBm as
advertised by a0:55:4f:27:bd:01
[ 682.255302] wlp2s0: disassociated from a0:55:4f:27:bd:01 (Reason:
1=UNSPECIFIED)
[ 682.304134] wlp2s0: failed to remove key (1, ff:ff:ff:ff:ff:ff)
from hardware (-22)
[ 685.809837] wlp2s0: authenticate with a0:55:4f:27:bd:01
dmesg | less -N
It will show output along with line numbers
Output :
1 [ 0.000000] microcode: microcode updated early to revision 0x21,
date = 2017-11-20
2 [ 0.000000] random: get_random_bytes called from
start_kernel+0x42/0x504 with crng_init=0
3 [ 0.000000] Linux version 4.13.0-26-generic (buildd@lgw01-
amd64-031) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-
6ubuntu1~16.04.5)) #2 3 9~16.04.2-Ubuntu SMP Tue Jan 9 22:00:44
UTC 2018 (Ubuntu 4.13.0-26.29~16.04.2-generic 4.13.13)
4 [ 0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-4.13.0-
26-generic.efi.signed root=UUID=993a37f2-7ea9-43a3-b652-5b26bb879797
ro qu 4 iet splash vt.handoff=7
5 [ 0.000000] KERNEL supported cpus:
6 [ 0.000000] Intel GenuineIntel
7 [ 0.000000] AMD AuthenticAMD
8 [ 0.000000] Centaur CentaurHauls
9 [ 0.000000] x86/fpu: Supporting XSAVE feature 0x001: 'x87
floating point registers'
10 [ 0.000000] x86/fpu: Supporting XSAVE feature 0x002: 'SSE
registers'
11 [ 0.000000] x86/fpu: Supporting XSAVE feature 0x004: 'AVX
registers'
12 [ 0.000000] x86/fpu: xstate_offset[2]: 576,
xstate_sizes[2]: 256
less -F filename

eg. less -F /home/mandeep/test/first.erl


It will not give any output, since file can be displayed in single screen.
less /home/mandeep/test/first.erl
These are contents of above tested file, it can be displayed on single screen.
-module(first).
-export([fib/1]).

fib(X) when X
1;
fib(X) when X >= 2 ->
fib(X - 1) + fib(X - 2).

15.more command

more command is used to view the text files in the command prompt, displaying
one screen at a time in case the file is large (For example log files). The more
command also allows the user do scroll up and down through the page. The
syntax along with options and command is as follows. Another application of
more is to use it with some other command after a pipe. When the output is
large, we can use more command to see output one by one.
Syntax:
more [-options] [-num] [+/pattern] [+linenum] [file_name]
 [-options]: any option that you want to use in order to change the way
the file is displayed. Choose any one from the followings: (-d, -l, -f, -p, -c, -s,
-u)
 [-num]: type the number of lines that you want to display per screen.
 [+/pattern]: replace the pattern with any string that you want to find in the
text file.
 [+linenum]: use the line number from where you want to start displaying
the text content.
 [file_name]: name of the file containing the text that you want to display
on the screen.
While viewing the text file use these controls:
Enter key: to scroll down line by line.
Space bar: To go to the next page.
b key: To go to back one page.

Options:
 -d : Use this command in order to help the user to navigate. It displays
“[Press space to continue, ‘q’ to quit.]” and displays “[Press ‘h’ for
instructions.]” when wrong key is pressed.
Example:
more -d sample.txt
 -f : This option does not wrap the long lines and displays them as such.
Example:
more -f sample.txt
 -p : This option clears the screen and then displays the text.
Example:
more -p sample.txt

 -c : This command is used to display the pages on the same area by


overlapping the previously displayed text.
Example:
more -c sample.txt
 -s : This option squeezes multiple blank lines into one single blank line.
Example:
more -s sample.txt

 -u : This option omits the underlines.


Example:
more -u sample.txt
 +/pattern : This option is used to search the string inside your text
document. You can view all the instances by navigating through the result.
Example:
more +/reset sample.txt

 +num : This option displays the text after the specified number of lines of
the document.
Example:
more +30 sample.txt
Using more to Read Long Outputs: We use more command after a pipe to
see long outputs. For example, seeing log files, etc.
cat a.txt | more

16.grep command

The grep filter searches a file for a particular pattern of characters, and displays
all lines that contain that pattern. The pattern that is searched in the file is
referred to as the regular expression (grep stands for globally search for regular
expression and print out). 
Syntax: 
 
grep [options] pattern [files]
 
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
-e exp : Specifies expression with this option. Can use multiple
times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
with each such part on a separate output line.

-A n : Prints searched line and nlines after the result.


-B n : Prints searched line and n line before the result.
-C n : Prints searched line and n lines after before the result.
 
Sample Commands
Consider the below file as an input. 
 

$cat > geekfile.txt


 
unix is great os. unix is opensource. unix is free os.
learn operating system.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a
powerful.
1. Case insensitive search : The -i option enables to search for a string case
insensitively in the give file. It matches the words like “UNIX”, “Unix”, “unix”. 
 
$grep -i "UNix" geekfile.txt
Output: 
 
unix is great os. unix is opensource. unix is free os.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a
powerful.
2. Displaying the count of number of matches : We can find the number of
lines that matches the given string/pattern 
 
$grep -c "unix" geekfile.txt
Output: 
 
2
3. Display the file names that matches the pattern : We can just display the
files that contains the given string/pattern. 
 
$grep -l "unix" *

or

$grep -l "unix" f1.txt f2.txt f3.xt f4.txt


Output: 
 
geekfile.txt
4. Checking for the whole words in a file : By default, grep matches the given
string/pattern even if it found as a substring in a file. The -w option to grep
makes it match only the whole words. 
 

$ grep -w "unix" geekfile.txt


Output: 
 
unix is great os. unix is opensource. unix is free os.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a
powerful.
5. Displaying only the matched pattern : By default, grep displays the entire
line which has the matched string. We can make the grep to display only the
matched string by using the -o option. 
 
$ grep -o "unix" geekfile.txt
Output: 
 
unix
unix
unix
unix
unix
unix
6. Show line number while displaying the output using grep -n : To show
the line number of file with the line matched. 
 
$ grep -n "unix" geekfile.txt
Output: 
 
1:unix is great os. unix is opensource. unix is free os.
4:uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a
powerful.
7. Inverting the pattern match : You can display the lines that are not
matched with the specified search sting pattern using the -v option. 
 
$ grep -v "unix" geekfile.txt
Output: 
 
learn operating system.
Unix linux which one you choose.
8. Matching the lines that start with a string : The ^ regular expression
pattern specifies the start of a line. This can be used in grep to match the lines
which start with the given string or pattern. 
 
$ grep "^unix" geekfile.txt
Output: 
 
unix is great os. unix is opensource. unix is free os.
9. Matching the lines that end with a string : The $ regular expression
pattern specifies the end of a line. This can be used in grep to match the lines
which end with the given string or pattern. 
 
$ grep "os$" geekfile.txt
10.Specifies expression with -e option. Can use multiple times : 
 
$grep –e "Agarwal" –e "Aggarwal" –e "Agrawal" geekfile.txt
11. -f file option Takes patterns from file, one per line. 
 
$cat pattern.txt

Agarwal
Aggarwal
Agrawal
 
$grep –f pattern.txt geekfile.txt
12. Print n specific lines from a file:  -A prints the searched line and n lines
after the result, -B prints the searched line and n lines before the result, and -C
prints the searched line and n lines after and before the result. 
Syntax:
$grep -A[NumberOfLines(n)] [search] [file]

$grep -B[NumberOfLines(n)] [search] [file]

$grep -C[NumberOfLines(n)] [search] [file]


Example:
$grep -A1 learn geekfile.txt
Output:  
learn operating system.
Unix linux which one you choose.
--
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a
powerful.

(Prints the searched line along with the next n lines (here n = 1
(A1).)
(Will print each and every occurance of the found line, seperating
each output by --)
(Output pattern remains the same for -B and -C respectively)

17.vi command
The default editor that comes with the UNIX operating system is called vi (visual
editor). Using vi editor, we can edit an existing file or create a new file from
scratch. we can also use this editor to just read a text file.
Syntax:
vi filename

Input:
Output:

Modes of Operation in vi editor There are three modes of operation in vi:


 Command Mode: When vi starts up, it is in Command Mode. This mode
is where vi interprets any characters we type as commands and thus does
not display them in the window. This mode allows us to move through a file,
and to delete, copy, or paste a piece of text.
To enter into Command Mode from any other mode, it requires pressing
the [Esc] key. If we press [Esc] when we are already in Command Mode,
then vi will beep or flash the screen.
 Insert mode: This mode enables you to insert text into the file.
Everything that’s typed in this mode is interpreted as input and finally, it is
put in the file. The vi always starts in command mode. To enter text, you
must be in insert mode. To come in insert mode you simply type i. To get out
of insert mode, press the Esc key, which will put you back into command
mode.
 Last Line Mode(Escape Mode): Line Mode is invoked by typing a colon
[:], while vi is in Command Mode. The cursor will jump to the last line of the
screen and vi will wait for a command. This mode enables you to perform
tasks such as saving files, executing commands.

Starting the vi Editor

There are following way you can start using vi editor :


Commands and their Description

 vi filename:  Creates a new file if it already not exist, otherwise opens


existing file.
 vi -R filename  : Opens an existing file in read only mode.
 view filename : Opens an existing file in read only mode.
Moving within a File(Navigation):
To move around within a file without affecting text must be in command mode
(press Esc twice). Here are some of the commands can be used to move
around one character at a time.
Commands and their Description
 k : Moves the cursor up one line.
 j  : Moves the cursor down one line.
 h : Moves the cursor to the left one character position.
 l  : Moves the cursor to the right one character position.
 0 or |  : Positions cursor at beginning of line.
 $ : Positions cursor at end of line.
 W : Positions cursor to the next word.
 B  : Positions cursor to previous word.
 ( : Positions cursor to beginning of current sentence.
 ) : Positions cursor to beginning of next sentence.
 H  : Move to top of screen.
 nH : Moves to nth line from the top of the screen.
 M : Move to middle of screen.
 L : Move to bottom of screen.
 nL  : Moves to nth line from the bottom of the screen.
 colon along with x  : Colon followed by a number would position the
cursor on line number represented by x.
Control Commands(Scrolling): There are following useful commands which
can used along with Control Key:
Commands and their Description:
 CTRL+d  : Move forward 1/2 screen.
 CTRL+f  : Move forward one full screen.
 CTRL+u  : Move backward 1/2 screen.
 CTRL+b  : Move backward one full screen.
 CTRL+e  : Moves screen up one line.
 CTRL+y  : Moves screen down one line.
 CTRL+u  : Moves screen up 1/2 page.
 CTRL+d  : Moves screen down 1/2 page.
 CTRL+b  : Moves screen up one page.
 CTRL+f  : Moves screen down one page.
 CTRL+I : Redraws screen.
Editing and inserting in Files(Entering and Replacing Text): To edit the file,
we need to be in the insert mode. There are many ways to enter insert mode
from the command mode.
 i  : Inserts text before current cursor location.
 I  : Inserts text at beginning of current line.
 a : Inserts text after current cursor location.
 A  : Inserts text at end of current line.
 o : Creates a new line for text entry below cursor location.
 O  : Creates a new line for text entry above cursor location.
 r : Replace single character under the cursor with the next character
typed.
 R  : Replaces text from the cursor to right.
 s : Replaces single character under the cursor with any number of
characters.
 S  :Replaces entire line.
Deleting Characters: Here is the list of important commands which can be
used to delete characters and lines in an opened file.
 X  Uppercase: Deletes the character before the cursor location.
 x Lowercase : Deletes the character at the cursor location.
 Dw  : Deletes from the current cursor location to the next word.
 d^ : Deletes from current cursor position to the beginning of the line.
 d$  : Deletes from current cursor position to the end of the line.
 Dd : Deletes the line the cursor is on.
Copy and Past Commands: Copy lines or words from one place and paste
them on another place by using the following commands.
 Yy  : Copies the current line.
 9yy  : Yank current line and 9 lines below.
 p : Puts the copied text after the cursor.
 P  : Puts the yanked text before the cursor.
Save and Exit Commands of the ex Mode : Need to press [Esc] key followed
by the colon (:) before typing the following commands:

 q : Quit
 q! : Quit without saving changes i.e. discard changes.
 r fileName : Read data from file called fileName.
 wq : Write and quit (save and exit).
 w fileName  : Write to file called fileName (save as).
 w! fileName : Overwrite to file called fileName (save as forcefully).
 !cmd : Runs shell commands and returns to Command mode.
Searching and Replacing in (ex Mode): vi also has powerful search and
replace capabilities. The formal syntax for searching is:
:s/string
For example, suppose we want to search some text for the
string “geeksforgeeks” Type the following and press ENTER:
:s/geeksforgeeks
Input:

Output: finding the first match for “geeksforgeeks” in text will then be


highlighted.

The syntax for replacing one string with another string in the current line is:
:s/pattern/replace/
Here “pattern” represents the old string and “replace” represents the new string.
For example, to replace each occurrence of the word “geeks” in a line with
“geeksforgeeks” type:
:s/geeksforgeeks/gfg/
Input:

Output:
The syntax for replacing every occurrence of a string in the entire text is similar.
The only difference is the addition of a “%” in front of the “s”:
:%s/pattern/replace/
Thus repeating the previous example for the entire text instead of just for a
single line would be:
:%s/gfg/geeksforgeeks/

18.hard link and soft link command


A link in UNIX is a pointer to a file. Like pointers in any programming languages,
links in UNIX are pointers pointing to a file or a directory. Creating links is a kind
of shortcuts to access a file. Links allow more than one file name to refer to the
same file, elsewhere. 
There are two types of links :
1. Soft Link or Symbolic links
2. Hard Links
These links behave differently when the source of the link (what is being linked
to) is moved or removed. Symbolic links are not updated (they merely contain a
string which is the path name of its target); hard links always refer to the source,
even if moved or removed. 
For example, if we have a file a.txt. If we create a hard link to the file and then
delete the file, we can still access the file using hard link. But if we create a soft
link of the file and then delete the file, we can’t access the file through soft link
and soft link becomes dangling. Basically hard link increases reference count of
a location while soft links work as a shortcut (like in Windows) 
1. Hard Links 
 

 Each hard linked file is assigned the same Inode value as the original,
therefore they reference the same physical file location. Hard links more
flexible and remain linked even if the original or linked files are moved
throughout the file system, although hard links are unable to cross different
file systems.
 ls -l command shows all the links with the link column shows number of
links.
 Links have actual file contents
 Removing any link, just reduces the link count, but doesn’t affect other
links.
 Even if we change the filename of the original file then also the hard links
properly work.
 We cannot create a hard link for a directory to avoid recursive loops.
 If original file is removed then the link will still show the content of the file.
 The size of any of the hard link file is same as the original file and if we
change the content in any of the hard links then size of all hard link files are
updated.
 The disadvantage of hard links is that it cannot be created for files on
different file systems and it cannot be created for special files or directories.
 Command to create a hard link is: 
 
$ ln [original filename] [link name]

 
2. Soft Links 
 
 A soft link is similar to the file shortcut feature which is used in Windows
Operating systems. Each soft linked file contains a separate Inode value that
points to the original file. As similar to hard links, any changes to the data in
either file is reflected in the other. Soft links can be linked across different file
systems, although if the original file is deleted or moved, the soft linked file
will not work correctly (called hanging link).
 ls -l command shows all links with first column value l? and the link points
to original file.
 Soft Link contains the path for original file and not the contents.
 Removing soft link doesn’t affect anything but removing original file, the
link becomes “dangling” link which points to nonexistent file.
 A soft link can link to a directory.
 Size of a soft link is equal to the name of the file for which the soft link is
created. E.g If name of file is file1 then size of it’s soft link will be 5 bytes
which is equal to size of name of original file.
 If we change the name of the original file then all the soft links for that file
become dangling i.e. they are worthless now.
 Link across file systems: If you want to link files across the file systems,
you can only use symlinks/soft links.
 Command to create a Soft link is: 
 
$ ln -s [original filename] [link name]

You might also like