Linux Unit II

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 70

UNIT – II

1. Linux commands and Utilities: alias, at, atrm


alias command
alias command instructs the shell to replace one string with another string while
executing the commands.
When we often have to use a single big command multiple times, in those cases, we
create something called as alias for that command. Alias is like a shortcut command
which will have same functionality as if we are writing the whole command.
Syntax:
alias [-p] [name[=value] ... ]

Creating an alias :
Syntax:
alias name="value"

Creating an Unalias : Removing an existing alias is known as unaliasing.


Syntax:
unalias [alias name]

Options for Alias command:


 -p option : This option prints all the defined aliases is reusable format.
Syntax:
alias -p
 –help option : It displayes help Information.
Syntax:
alias --help

How to remove an alias?


We use unailas command for this purpose.

How to permanently store aliases across sessions?


We can store aliases in shell configuration files. For example for Bash Shell, we can
write in ~/.bashrc.
alias CD="cd Desktop"
at Command in Linux with Examples

at command is a command-line utility that is used to schedule a command to be


executed at a particular time in the future. Jobs created with at command are
executed only once. The at command can be used to execute any program or
mail at any time in the future. It executes commands at a particular time and
accepts times of the form HH:MM to run a job at a specific time of day. The
following expression like noon, midnight, teatime, tomorrow, next week, next
Monday, etc. could be used with at command to schedule a job.
Syntax:
at [OPTION...] runtime
Installation of at command
For Ubuntu/Debian :
sudo apt-get update
sudo apt-get install at
For CentOS/Fedora :
sudo yum install at
Working with at command
1. Command to list the user’s pending jobs:
at -l
or
atq

2. Schedule a job for the coming Monday at a time twenty minutes later than
the current time:
at Monday +20 minutes
3. Schedule a job to run at 1:45 Aug 12 2020:
at 1:45 081220
4. Schedule a job to run at 3pm four days from now:
at 3pm + 4 days
5. Schedule a job to shutdown the system at 4:30 today:
# echo "shutdown -h now" | at -m 4:30
6. Schedule a job to run five hour from now:
at now +5 hours
7. at -r or atrm command is used to deletes job , here used to deletes job 11 .
at -r 11
or
atrm 11

Atrm command with examples


atrm command is used to remove the specified jobs. To remove a job, its job
number is passed in the command. A user can only delete jobs that belong to him.
Only superuser can delete any job even if that belongs to another user.
Syntax:
atrm [-V] job [job...]
Options:
 -V : Used to print the version number
atrm -V

job : Job number of the job which is to be deleted. To see the list of the pending
jobs use following:

Example 1: Deleting job number 22.


atrm 22

Example 2: Deleting multiple jobs in single atrm command:


atrm 21 26
Alternative command for atrm:
Syntax:
at -r Job
Example 1: Deleting single job:
at -r 24

Example 2: Deleting multiple jobs:


at -r 25 27
2. File Manipulation commands: Files-Creating, Moving,
Copying and Deleting Files

1. Creating Files

touch command can be used to create a new file. It will create and open a new blank
file if the file with a filename does not exist. And in case the file already exists then
the file will not be affected.
$touch filename

Create File with cat Command


The cat command is short for concatenate. It can be used to output the contents of
several files, one file, or even part of a file. If the file doesn’t exist, the Linux cat
command will create it.
To create an empty file using cat, enter the following:
cat > test3.txt
Create File with echo Command
The echo command will duplicate whatever you specify in the command, and put
the copy into a file.
Enter the following:
echo 'Random sample text' > test4.txt
Create a New File With the Redirect Operator
A redirection operator is a name for a character that changes the destination where
the results are displayed.
Right angle bracket >
This symbol tells the system to output results into whatever you specify next. The
target is usually a filename. You can use this symbol by itself to create a new file:
> test2.txt

2. Displaying File Contents

cat command can be used to display the contents of a file. This command will
display the contents of the ‘filename’ file. And if the output is very large then we
could use more or less to fit the output on the terminal screen otherwise the content
of the whole file is displayed at once.
$cat filename

3. Copying a File

cp command could be used to create the copy of a file. It will create the new file in
destination with the same name and content as that of the file ‘filename’.
$cp source/filename destination/

4. Moving a File

mv command could be used to move a file from source to destination. It will remove
the file filename from the source folder and would be creating a file with the same
name and content in the destination folder.
$mv source/filename destination/

5. Renaming a File

mv command could be used to rename a file. It will rename the filename to


new_filename or in other words, it will remove the filename file and would be
creating a new file with the new_filename with the same content and name as that of
the filename file.
$mv filename new_filename
6. Deleting a File

rm command could be used to delete a file. It will remove the filename file from the
directory.
$rm filename

3. Directory related commands: cd, mkdir, rm, rmdir,ls,


pwd, mv, tree

1. Creating Directories

We will now understand how to create directories. Directories are created by the
following command −
$mkdir dirname
Here, directory is the absolute or relative pathname of the directory you want to
create. For example, the command −
$mkdir mydir
$
Creates the directory mydir in the current directory. Here is another example −
$mkdir /tmp/test-dir
$
This command creates the directory test-dir in the /tmp directory.
The mkdir command produces no output if it successfully creates the requested
directory.
If you give more than one directory on the command line, mkdir creates each of the
directories. For example, −
$mkdir docs pub
Creates the directories docs and pub under the current directory.

2. Changing Directories

You can use the cd command to do more than just change to a home directory. You
can use it to change to any directory by specifying a valid absolute or relative path.
The syntax is as given below −
$cd dirname
Here, dirname is the name of the directory that you want to change to. For example,
the command −
$cd /usr/local/bin
$Changes to the directory /usr/local/bin. From this directory, you
can cd to the directory /usr/home/amrood using the following relative
path −
$cd ../../home/amrood

3. Renaming Directories

The mv (move) command can also be used to rename a directory. The syntax is as
follows −
$mv olddir newdir
$
You can rename a directory mydir to yourdir as follows −
$mv mydir yourdir
$

4. Removing the Directories

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
5.ls command in LINUX
The ls is the list command in Linux. It will show the full list or content of your
directory. Just type ls and press the enter key. The whole content will be shown.

Linux ls command options


ls option Description

ls -a In Linux, hidden files start with . (dot) symbol and they are not visible in
the regular directory. The (ls -a) command will enlist the whole list of
the current directory including the hidden files.

ls -l It will show the list in a long list format.

ls -lh This command will show you the file sizes in human readable format.
Size of the file is very difficult to read when displayed in terms of byte.
The (ls -lh)command will give you the data in terms of Mb, Gb, Tb, etc.

ls -lhS If you want to display your files in descending order (highest at the top)
according to their size, then you can use (ls -lhS) command.

ls -l - -block- It is used to display the files in a specific size format. Here, in [SIZE]
size=[SIZE] you can assign size according to your requirement.

ls -d */ It is used to display only subdirectories.

ls -g or ls -lG With this you can exclude column of group information and owner.

ls -n It is used to print group ID and owner ID instead of their names.

ls -- This command is used to print list as colored or discolored.


color=[VALUE]

ls -li This command prints the index number if file is in the first column.

ls -p It is used to identify the directory easily by marking the directories with


a slash (/) line sign.

ls -r It is used to print the list in reverse order.

ls -R It will display the content of the sub-directories also.

ls -lX It will group the files with same extensions together in the list.

ls -lt It will sort the list by displaying recently modified filed at top.

ls ~ It gives the contents of home directory.

ls ../ It give the contents of parent directory.

ls --version It checks the version of ls command.


Linux ls -a command
It will give you the whole list of a directory including the hidden files also. In Linux,
hidden files start with a dot (.) and can't be seen in the regular directory.

In the above example, you can see the whole list of files, including the hidden files.
Linux ls -l command
The ls command will only display the files. But if you want your files to be displayed
in a long list format, then you can use ls -l command.
Here, as you can see the list in long list format.
Columns above indicate specific things:
Column 1 indicates information regarding file permission.
Column 2 indicates the number of links to the file.
Column 3 & 4 indicates the owner and group information.
Column 5 indicayes size of the file in bytes.
Column 6 shows th date and time on which the file was recently modified.
Column 7 shows the file or directory name.
Linux ls -l --block-size=[SIZE]
If you want to display the file size of your list in a particular format or size, then you
can use this command. Just put the size in place of [SIZE] as per your requirement.
Syntax:

Here, all file size has listed in Megabyte.


You can replace [SIZE] with the following measures:
K = Kilobyte
M = Megabyte
G = Gigabyte
T = Terabyte
P = Petabyte
E = Exabyte
Z = Zettabyte
Y = Yottabyte
Linux ls -d */
If you only want to display the sub-directories excluding all other files, you can use
this command.
The above result only shows sub-directories excluding all the other files.
Linux ls -g
If you don't want to display the owner information in your list, then you can exclude
this column with the help of this command.

Here owner column is excluded.

Linux ls -lG
If you don't want to display the group information in your list then you can exclude
this column with the help of this command.
Here group column is excluded.
Linux ls --color=[VALUE]
This command is used to colorize and decolorize the list. If you replace the [VALUE]
by 'auto', it will display the colored list. But, if you will replace the [VALUE] by
'never', it will decolorize the list.
Syntax:
ls --color=[VALUE]

Linux ls ~
Linux ls ~ command shows the contents of the home directory. Let us see the example
of ls ~ command.

Linux ls ../
This command contains the list of the parent directory.
In the given example, our current directory is Downloads, and by using ls ../ command,
we have listed out the content of its parent directory "home directory".
6. Tree command

In UNIX/LINUX systems, as well as MS-DOS and Microsoft Windows, tree is a


recursive directory listing program that produces a depth-indented listing of files. With
no arguments, tree lists the files in the current directory. When directory arguments are
given, tree lists all the files or directories found in the given directories each in turn.
Upon completion of listing all files and directories found, tree returns the total number
of files and directories listed. There are options to change the characters used in the
output, and to use color output.
Syntax :
$ tree [-adfgilnopqrstuxACDFNS] [-L level [-R]] [-H baseHREF] [-T title] [-o
filename]
[–nolinks] [-P pattern] [-I pattern] [–inodes] [–device] [–noreport] [–dirsfirst]
[–version] [–help] [directory …]

Options :
–help : Outputs a verbose usage listing.
–version : Outputs the version of tree.
-a : All files are printed. By default, tree does not print hidden files (those beginning
with a dot `.’). In no event does tree print the file system constructs `.’ (current
directory) and `..’ (previous directory).
-d : List directories only.
-f : Prints the full path prefix for each file.
-i : Tree will not print the indentation lines. Useful when used in conjunction with the -
f option.
-l : Follows symbolic links to directories as if they were directories. Links that would
result in a recursive loop are avoided.
-x : Stay on the current file system only, as with find -xdev.
-P pattern : List only those files that match the wild-card pattern.
Note : you must use the -a option to also consider those files beginning with a dot `.’
for matching. Valid wildcard operators are `*’ (any zero or more characters), `?’ (any
single character), `[…]’ (any single character listed between brackets (optional –
(dash) for character range may be used: ex: [A-Z]), and `[^…]’ (any single character
not listed in brackets) and `|’ separates alternate patterns.
-I pattern : Do not list those files that match the wild-card pattern.
–prune : Makes tree prune empty directories from the output, useful when used in
conjunction with -P or -I.
–filelimit # : Do not descend directories that contain more than # entries.
–timefmt format : Prints (implies -D) and formats the date according to the format
string which uses the strftime syntax.
–noreport : Omits printing of the file and directory report at the end of the tree listing.
-p : Print the protections for each file (as per ls -l).
-s : Print the size of each file along with the name.
-u : Print the username, or UID # if no username is available, of the file.
-g : Print the group name, or GID # if no group name is available, of the file.
-D : Print the date of the last modification time for the file listed.
–inodes : Prints the inode number of the file or directory
–device : Prints the device number to which the file or directory belongs
-F : Append a `/’ for directories, a `=’ for socket files, a `*’ for executable files and a
`|’ for FIFO’s, as per ls -F
-q : Print non-printable characters in file names as question marks instead of the
default carrot notation.
-N : Print non-printable characters as is instead of the default carrot notation.
-r : Sort the output in reverse alphabetic order.
-t : Sort the output by last modification time instead of alphabetically.
–dirsfirst : List directories before files.
-n : Turn colorization off always, over-ridden by the -C option.
-C : Turn colorization on always, using built-in color defaults if the LS_COLORS
environment variable is not set. Useful to colorize output to a pipe.
-A : Turn on ANSI line graphics hack when printing the indentation lines.
-S : Turn on ASCII line graphics (useful when using linux console mode fonts). This
option is now equivalent to `–charset=IBM437′ and will eventually be depreciated.
-L level : Max display depth of the directory tree.
-R : Recursively cross down the tree each level directories (see -L option), and at each
of them execute tree again adding `-o 00Tree.html’ as a new option.
-H baseHREF : Turn on HTML output, including HTTP references. Useful for ftp
sites. baseHREF gives the base ftp location when using HTML output. That is, the
local directory may be `/local/ftp/pub’, but it must be referenced as `ftp://host-
name.organization.domain/pub’ (baseHREF should be
`ftp://hostname.organization.domain’). Hint: don’t use ANSI lines with this option, and
don’t give more than one directory in the directory list. If you want to use colors via
CSS stylesheet, use the -C option in addition to this option to force color output.
-T title : Sets the title and H1 header string in HTML output mode.
–charset charset : Set the character set to use when outputting HTML and for line
drawing.
–nolinks : Turns off hyperlinks in HTML output.
-o file name : Send output to file name.
Examples :
1. How to install tree in Unix/Linux.
By default the tree command is not installed. Type the following command to install
the same on a RHEL / CentOS / Fedora Linux using yum command :
# yum install tree
If you are using Debian / Mint / Ubuntu Linux, type the following apt-get command to
install the tree command :
$ sudo apt install tree
If you are using Apple OS X, type:
brew install tree
2. Display the tree hierarchy of a directory
$ tree -a ./GFG
Output :

3. List files with entered pattern


$ tree -P sample* .
Output :

4. List those directories which have greater ‘N’ number of files/directories


$ tree --filelimit 3 ./GFG
5. List files with their permissions.
$ tree -p ./GFG
Output :

6. Prints the device number to which the file or directory belongs.


$ tree --device ./GFG
Output :

7. Prints the output by last modification time instead of alphabetically.


$ tree -t ./GFG
Output :
7. pwd command in Linux with Examples
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.

4. Filters: cat, grep, cut, wc, sort, more, pipe examples.


Filters are programs that take plain text(either stored in a file or produced by another
program) as standard input, transforms it into a meaningful format, and then returns it
as standard output. Linux has a number of filters. Some of the most commonly used
filters are explained below:

1. cat : Displays the text of the file line by line .


Syntax:
cat [path]

2. 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 global 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 given 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:

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 is 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 string 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.

cut command in LINUX


The cut command in LINUX is a command 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. Basically the cut command slices a line and
extracts the text. It is necessary to specify option with command otherwise it gives
error. If more than one file name is provided then data from each file is not precedes by
its file name.
Syntax:
cut OPTION... [FILE]...
Let us consider two files having name state.txt and capital.txt contains 5 names of the
Indian states and capitals respectively.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Without any option specified it displays error.
$ cut state.txt
cut: you must specify a list of bytes, characters, or fields
Try 'cut --help' for more information.
Options and their Description with examples:
1. -b(byte): To extract the specific bytes, you need to follow -b option with the list of
byte numbers separated by comma. Range of bytes can also be specified using the
hyphen(-). It is necessary to specify list of byte numbers otherwise it gives error. Tabs
and backspaces are treated like as a character of 1 byte.
List without ranges
$ cut -b 1,2,3 state.txt
And
Aru
Ass
Bih
Chh

List with ranges


$ cut -b 1-3,5-7 state.txt
Andra
Aruach
Assm
Bihr
Chhtti
It uses a special form for selecting bytes from beginning upto the end of the line:
In this, 1- indicate from 1st byte to end byte of a line
$ cut -b 1- state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
In this, -3 indicate from 1st byte to 3rd byte of a line
$ cut -b -3 state.txt
And
Aru
Ass
Bih
Chh
2. -c (column): To cut by character use the -c option. This selects the characters given
to the -c option. This can be a list of numbers separated comma or a range of numbers
separated by hyphen(-). Tabs and backspaces are treated as a character. It is necessary
to specify list of character numbers otherwise it gives error with this option.
Syntax:
$cut -c [(k)-(n)/(k),(n)/(n)] filename
Here,k denotes the starting position of the character and n denotes the ending position
of the character in each line, if k and n are separated by “-” otherwise they are only the
position of character in each line from the file taken as an input.
$ cut -c 2,5,7 state.txt
nr
rah
sm
ir
hti
Above cut command prints second, fifth and seventh character from each line of the
file.
$ cut -c 1-7 state.txt
Andhra
Arunach
Assam
Bihar
Chhatti
Above cut command prints first seven characters of each line from the file.
Cut uses a special form for selecting characters from beginning upto the end of the line:
$ cut -c 1- state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh

Above command prints starting from first character to end. Here in command only
starting
position is specified and the ending position is omitted.

$ cut -c -5 state.txt
Andhr
Aruna
Assam
Bihar
Chhat

Above command prints starting position to the fifth character. Here the starting position
is omitted and the ending position is specified.
3. -f (field): -c option is useful for fixed-length lines. Most unix files doesn’t have
fixed-length lines. To extract the useful information you need to cut by fields rather
than columns. List of the fields number specified must be separated by comma. Ranges
are not described with -f option. cut uses tab as a default field delimiter but can also
work with other delimiter by using -d option.
Note: Space is not considered as delimiter in UNIX.
Syntax:
$cut -d "delimiter" -f (field number) file.txt
Like in the file state.txt fields are separated by space if -d option is not used then it
prints whole line:
$ cut -f 1 state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
If -d option is used then it considered space as a field separator or delimiter:
$ cut -d " " -f 1 state.txt
Andhra
Arunachal
Assam
Bihar
Chhattisgarh
Command prints field from first to fourth of each line from the file.
Command:
$ cut -d " " -f 1-4 state.txt
Output:
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
4. –complement: As the name suggests it complement the output. This option can be
used in the combination with other options either with -f or with -c.
$ cut --complement -d " " -f 1 state.txt
Pradesh
Pradesh
Assam
Bihar
Chhattisgarh

$ cut --complement -c 5 state.txt


Andha Pradesh
Arunchal Pradesh
Assa
Biha
Chhatisgarh
5. –output-delimiter: By default the output delimiter is same as input delimiter that we
specify in the cut with -d option. To change the output delimiter use the option –output-
delimiter=”delimiter”.
$ cut -d " " -f 1,2 state.txt --output-delimiter='%'
Andhra%Pradesh
Arunachal%Pradesh
Assam
Bihar
Chhattisgarh
Here cut command changes delimiter(%) in the standard output between the fields
which is specified by using -f option .
6. –version: This option is used to display the version of cut which is currently running
on your system.
$ cut --version
cut (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.

1. How to use tail with pipes(|): The cut command can be piped with many other
commands of the unix. In the following example output of the cat command is given as
input to the cut command with -f option to sort the state names coming from file
state.txt in the reverse order.
$ cat state.txt | cut -d ' ' -f 1 | sort -r
Chhattisgarh
Bihar
Assam
Arunachal
Andhra
It can also be piped with one or more filters for additional processing. Like in the
following example, we are using cat, head and cut command and whose output is stored
in the file name list.txt using directive(>).
$ cat state.txt | head -n 3 | cut -d ' ' -f 1 > list.txt

$ cat list.txt
Andhra
Arunachal
Assam

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.

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

SORT command in Linux/Unix with examples


SORT command is used to sort a file, arranging the records in a particular order. By
default, the sort command sorts file assuming the contents are ASCII. Using options in
the sort command can also be used to sort numerically.
 SORT command sorts the contents of a text file, line by line.
 sort is a standard command-line program that prints the lines of its input or
concatenation of all files listed in its argument list in sorted order.
 The sort command is a command-line utility for sorting lines of text files. It
supports sorting alphabetically, in reverse order, by number, by month, and can also
remove duplicates.
 The sort command can also sort by items not at the beginning of the line, ignore
case sensitivity, and return whether a file is sorted or not. Sorting is done based on
one or more sort keys extracted from each line of input.
 By default, the entire input is taken as the sort key. Blank space is the default field
separator.
The sort command follows these features as stated below:
1. Lines starting with a number will appear before lines starting with a letter.
2. Lines starting with a letter that appears earlier in the alphabet will appear before
lines starting with a letter that appears later in the alphabet.
3. Lines starting with a lowercase letter will appear before lines starting with the same
letter in uppercase.
Examples
Suppose you create a data file with name file.txt:
Command :
$ cat > file.txt
abhishek
chitransh
satish
rajan
naveen
divyam
harsh
Sorting a file: Now use the sort command
Syntax :
$ sort filename.txt
Command:
$ sort file.txt

Output :
abhishek
chitransh
divyam
harsh
naveen
rajan
satish
Note: This command does not actually change the input file, i.e. file.txt.
Sort function with mix file i.e. uppercase and lower case: When we have a mix file with
both uppercase and lowercase letters then first the upper case letters would be sorted
following with the lower case letters.
Example:
Create a file mix.txt
Command :
$ cat > mix.txt
abc
apple
BALL
Abc
bat
Now use the sort command
Command :
$ sort mix.txt
Output :
Abc
BALL
abc
apple
bat
Options with sort function:
1. -o Option: Unix also provides us with special facilities like if you want to write
the output to a new file, output.txt, redirects the output like this or you can also use the
built-in sort option -o, which allows you to specify an output file.
Using the -o option is functionally the same as redirecting the output to a file.
Note: Neither one has an advantage over the other.
Example: The input file is the same as mentioned above.
Syntax:
$ sort inputfile.txt > filename.txt
$ sort -o filename.txt inputfile.txt
Command:
$ sort file.txt > output.txt
$ sort -o output.txt file.txt
$ cat output.txt
Output :
abhishek
chitransh
divyam
harsh
naveen
rajan
satish
2. -r Option: Sorting In Reverse Order: You can perform a reverse-order sort using the -
r flag. the -r flag is an option of the sort command which sorts the input file in reverse
order i.e. descending order by default.
Example: The input file is the same as mentioned above.
Syntax :
$ sort -r inputfile.txt
Command :
$ sort -r file.txt
Output :
satish
rajan
naveen
harsh
divyam
chitransh
abhishek
3. -n Option: To sort a file numerically used –n option. -n option is also predefined in
Unix as the above options are. This option is used to sort the file with numeric data
present inside.
Example :
Let us consider a file with numbers:
Command :
$ cat > file1.txt
50
39
15
89
200
Syntax:
$ sort -n filename.txt
Command :
$ sort -n file1.txt
Output :
15
39
50
89
200
4. -nr option: To sort a file with numeric data in reverse order we can use the
combination of two options as stated below.
Example: The numeric file is the same as above.
Syntax :
$ sort -nr filename.txt
Command :
$ sort -nr file1.txt
Output :
200
89
50
39
15
5. -k Option: Unix provides the feature of sorting a table on the basis of any column
number by using -k option.
Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the
second column.
Example :
Let us create a table with 2 columns
$ cat > employee.txt
manager 5000
clerk 4000
employee 6000
peon 4500
director 9000
guard 3000
Syntax :
$ sort -k filename.txt
Command :
$ sort -k 2n employee.txt
guard 3000
clerk 4000
peon 4500
manager 5000
employee 6000
director 9000
6. -c option: This option is used to check if the file given is already sorted or not &
checks if a file is already sorted pass the -c option to sort. This will write to standard
output if there are lines that are out of order. The sort tool can be used to understand if
this file is sorted and which lines are out of order
Example :
Suppose a file exists with a list of cars called cars.txt.
Audi
Cadillac
BMW
Dodge
Syntax :
$ sort -c filename.txt
Command :
$ sort -c cars.txt
Output :
sort: cars.txt:3: disorder: BMW
Note : If there is no output then the file is considered to be already sorted
7. -u option: To sort and remove duplicates pass the -u option to sort. This will write a
sorted list to standard output and remove duplicates.
This option is helpful as the duplicates being removed give us a redundant file.
Example: Suppose a file exists with a list of cars called cars.txt.
Audi
BMW
Cadillac
BMW
Dodge
Syntax :
$ sort -u filename.txt
Command :
$ sort -u cars.txt
$ cat cars.txt
Output :
Audi
BMW
Cadillac
Dodge
8. -M Option: To sort by month pass the -M option to sort. This will write a sorted list
to standard output ordered by month name.
Example:
Suppose the following file exists and is saved as months.txt
$ cat > months.txt
February
January
March
August
September

Syntax :
$ sort -M filename.txt
Using The -M option with sort allows us to order this file.
Command :
$ sort -M months.txt
$ cat months.txt
Output :
January
February
March
August
September

more command in Linux with Examples


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

Piping in Unix or Linux


A pipe is a form of redirection (transfer of standard output to some other destination)
that is used in Linux and other Unix-like operating systems to send the output of one
command/program/process to another command/program/process for further
processing. The Unix/Linux systems allow stdout of a command to be connected to
stdin of another command. You can make it do so by using the pipe character ‘|’.
Pipe is used to combine two or more commands, and in this, the output of one command
acts as input to another command, and this command’s output may act as input to the
next command and so on. It can also be visualized as a temporary connection between
two or more commands/ programs/ processes. The command line programs that do the
further processing are referred to as filters.
This direct connection between commands/ programs/ processes allows them to operate
simultaneously and permits data to be transferred between them continuously rather
than having to pass it through temporary text files or through the display screen.
Pipes are unidirectional i.e data flows from left to right through the pipeline.
Syntax :
command_1 | command_2 | command_3 | .... | command_N
Example :
1. Listing all files and directories and give it as input to more command.
$ ls -l | more
Output :

The more command takes the output of $ ls -l as its input. The net effect of this
command is that the output of ls -l is displayed one screen at a time. The pipe acts as a
container which takes the output of ls -l and gives it to more as input. This command
does not use a disk to connect standard output of ls -l to the standard input of more
because pipe is implemented in the main memory.
In terms of I/O redirection operators, the above command is equivalent to the following
command sequence.
$ ls -l -> temp
more -> temp (or more temp)
[contents of temp]
rm temp
Output :

Output of the above two commands is same.


2. Use sort and uniq command to sort a file and print unique values.
$ sort record.txt | uniq
This will sort the given file and print the unique values only.
Output :

3. Use head and tail to print lines in a particular range in a file.


$ cat sample2.txt | head -7 | tail -5
This command select first 7 lines through (head -7) command and that will be input to
(tail -5) command which will finally print last 5 lines from that 7 lines.
Output :

4. Use ls and find to list and print all lines matching a particular pattern in matching
files.
$ ls -l | find ./ -type f -name "*.txt" -exec grep "program" {} \;
This command select files with .txt extension in the given directory and search for
pattern like “program” in the above example and print those ine which have program in
them.
Output :

5. Use cat, grep, tee and wc command to read the particular entry from user and store in
a file and print line count.
$ cat result.txt | grep "Rajat Dua" | tee file2.txt | wc -l
This command select Rajat Dua and store them in file2.txt and print total number of
lines matching Rajat Dua
Output :
5. Tools and utilites: find, locate, date, cal, gzip, gunzip,
zcat, man, tar
find command in linux
Finding Files by Name
In order to find a file by name, simply type:
find -name "File1"
This is a case sensitive search, so it returned just one file:
./File1
If we want to run a case insensitive search, we can do this:
find -iname "File1"
This search will return both uppercase and lowercase results:
./file1

./File1
What if we only want to return files with names that don’t contain a certain string?
Then we will use:
find -not -name "file"
This will return all files that don’t contain the string “file” in them, and is applicable to
other strings.
Finding Files by Type
If you want to search for files by type, you can do so with the following command:
find -type typequery
Some examples of file types are:
f: Regular file
d: Directory
l: Symbolic link
c: Character devices
b: Block devices
In order to find a regular file called “file1” use:
find -type f -name "file1"
Finding Files by Time
You can find files based on access time (-atime), modified time (-mtime), and change
time (-ctime) flags.

Let’s find a file modified more than 5 days ago:


find / -ctime +5

Less than 1 day ago:


find / -ctime -1

More than 25 minutes ago:


find / -mmin +25
Finding Files by User or Group
The -user and -group flags can be used to find a file located by a specific user or group
Find all files owned by user “mc”:
find / -user mc
Find all files owned by group “mc” with the case sensitive name “mirrorlist.txt”
find / -group mc -name "mirrorlist.txt"

We can even find files based on permissions. This will list all files with 755
permissions:
find / -perm -755

Finding Files by Size


Find can filter files based on their size. SImply use the -size flag with the following size
conventions:
c: Bytes
k: Kilobytes
M: Megabytes
G: Gigabytes
b: 512-byte blocks
In order to find a file that is exactly 1GB in size, simply type in the phrase:
find / -size 1G

If it is greater than 1GB:


find / -size +1G

Less than 1GB:


find / -size -1G

Locate Command On Linux


An alternative to the find command is the locate command. The locate command builds
a database of files on the system, so searches tend to be faster.
It can be installed by running the following:
yum install locate

The database can be manually updated by running the following command:


Updated

To locate files by name, type:


locate filename

By default, this will return any file that has the string “filename” in its location. To
locate files only on the name of the actual file, use the –basename option:
locate -b filename

You can also use the wildcard characters, such as *. To find all files ending in .html,
type:
locate *.html

You can use pipe or redirect to take the standard output of the locate command and send
it to the standard input of another command, or to file:
locate *.html | grep file1
or
locate *.html > listoffiles.txt

date command in Linux with examples


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]
date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
Options with Examples
1: date (no option) : With no options, the date command displays the current date and
time, including the abbreviated day name, abbreviated month name, day of the month,
the time separated by colons, the time zone name, and the year.

Command:
$date
Output:
Tue Oct 10 22:55:01 PDT 2017
Note : Here unix system is configured in pacific daylight time.
2:-u Option: Displays the time in GMT(Greenwich Mean Time)/UTC(Coordinated
Universal Time )time zone.

Command:
$date -u
Output :
Wed Oct 11 06:11:31 UTC 2017
3: –date or -d Option: Displays the given date string in the format of date. But this will
not affect the system’s actual date and time value.Rather it uses the date and time given
in the form of string.
Syntax:

$date --date=" string "

Command:
$date --date="2/02/2010"
$date --date="Feb 2 2010"
Output:
Tue Feb 2 00:00:00 PST 2010
Tue Feb 2 00:00:00 PST 2010
4:Using –date option for displaying past dates:

Date and time of 2 years ago.

Command:
$date --date="2 year ago"
Output:
Sat Oct 10 23:42:15 PDT 2015
Date and time of 5 seconds ago.

Command:
$date --date="5 sec ago"
Output:
Tue Oct 10 23:45:02 PDT 2017

Date and time of previous day.

Command:
$date --date="yesterday"
Output:
Mon Oct 9 23:48:00 PDT 2017

Date and time of 2 months ago.

Command:
$date --date="2 month ago"
Output:
Thu Aug 10 23:54:51 PDT 2017

Date and time of 10 days ago.

Command:
$date --date="10 day ago"
Output:
Sat Sep 30 23:56:55 PDT 2017

5:Using –date option for displaying future date:

Date and time of upcoming particular week day.

Command:
$date --date="next tue"
Output:
Tue Oct 17 00:00:00 PDT 2017

Date and time after two days.

Command:
$date --date="2 day"
Output:
Fri Oct 13 00:05:52 PDT 2017

Date and time of next day.

Command:
$date --date="tomorrow"
Output:
Thu Oct 12 00:08:47 PDT 2017
Date and time after 1 year on the current day.

Command:
$date --date="1 year"
Output:
Thu Oct 11 00:11:38 PDT 2018
6:-s or –set Option: To set the system date and time -s or –set option is used.
Syntax:

$date --set="date to be set"

Command:
$date
Output:
Wed Oct 11 15:23:26 PDT 2017
Command:
$date --set="Tue Nov 13 15:23:34 PDT 2018"
$date
Output:
Tue Nov 13 15:23:34 PDT 2018
7:–file or -f Option: This is used to display the date string present at each line of file in
the date and time format.This option is similar to –date option but the only difference is
that in –date we can only give one date string but in a file we can give multiple date
strings at each line.
Syntax:

$date --file=file.txt

$cat >> datefile


Sep 23 2018
Nov 03 2019
Command:
$date --file=datefile
Output:
Sun Sep 23 00:00:00 PDT 2018
Sun Nov 3 00:00:00 PDT 2019
8:-r Option: This is used to display the last modified timestamp of a datefile .
Syntax:

$date -r file.txt
We can modify the timestamp of a datefile by using touch command.

$touch datefile

$date -r datefile
Wed Oct 11 15:54:18 PDT 2017
//this is the current date and time
$touch datefile
//The timestamp of datefile is changed using touch command.
This was done few seconds after the above date command’s output.
$date -r datefile
Wed Oct 11 15:56:23 PDT 2017
//display last modified time of datefile
9: List of Format specifiers used with date command:

%D: Display date as mm/dd/yy.


%d: Display the day of the month (01 to 31).
%a: Displays the abbreviated name for weekdays (Sun to Sat).
%A: Displays full weekdays (Sunday to Saturday).
%h: Displays abbreviated month name (Jan to Dec).
%b: Displays abbreviated month name (Jan to Dec).
%B: Displays full month name(January to December).
%m: Displays the month of year (01 to 12).
%y: Displays last two digits of the year(00 to 99).
%Y: Display four-digit year.
%T: Display the time in 24 hour format as HH:MM:SS.
%H: Display the hour.
%M: Display the minute.
%S: Display the seconds.
Syntax:

$date +%[format-option]
Examples:

Command:
$date "+%D"
Output:
10/11/17
Command:
$date "+%D %T"
Output:
10/11/17 16:13:27
Command:
$date "+%Y-%m-%d"
Output:
2017-10-11
Command:
$date "+%Y/%m/%d"
Output:
2017/10/11
Command:
$date "+%A %B %d %T %y"
Output:
Thursday October 07:54:29 12 17

cal command in Linux with Examples


If a user wants a quick view of the calendar in the Linux terminal, cal is the command
for you. By default, the cal command shows the current month calendar as output.
cal command is a calendar command in Linux which is used to see the calendar of a
specific month or a whole year.

Syntax:
cal [ [ month ] year]
The rectangular bracket means it is optional, so if used without an option, it will display
a calendar of the current month and year.
cal : Shows current month calendar on the terminal with the current date highlighted.

cal -y : Shows the calendar of the complete current year with the current date
highlighted.

cal 08 2000 : Shows calendar of selected month and year.


cal 2018 : Shows the whole calendar of the year.

cal 2018 | more : But year may not be visible in the same screen use more with cal use
spacebar to scroll down.
cal -3 : Shows calendar of previous, current and next month

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.
Gzip Command in Linux
gzip command compresses files. Each single file is compressed into a single file. The
compressed file consists of a GNU zip header and deflated data.
If given a file as an argument, gzip compresses the file, adds a “.gz” suffix, and deletes
the original file. With no arguments, gzip compresses the standard input and writes the
compressed file to standard output.
Difference between Gzip and zip command in Unix and when to use which command
ZIP and GZIP are two very popular methods of compressing files, in order to save
space, or to reduce the amount of time needed to transmit the files across the network,
or internet.
In general, GZIP is much better compared to ZIP, in terms of compression, especially
when compressing a huge number of files.
The common practice with GZIP, is to archive all the files into a single tarball before
compression. In ZIP files, the individual files are compressed and then added to the
archive.
When you want to pull a single file from a ZIP, it is simply extracted, then
decompressed. With GZIP, the whole file needs to be decompressed before you can
extract the file you want from the archive.
When pulling a 1MB file from a 10GB archive, it is quite clear that it would take a lot
longer in GZIP, than in ZIP.
GZIP’s disadvantage in how it operates, is also responsible for GZIP’s advantage. Since
the compression algorithm in GZIP compresses one large file instead of multiple
smaller ones, it can take advantage of the redundancy in the files to reduce the file size
even further.
If you archive and compress 10 identical files with ZIP and GZIP, the ZIP file would be
over 10 times bigger than the resulting GZIP file.

Syntax :
gzip [Options] [filenames]

Example:
$ gzip mydoc.txt
This command will create a compressed file of mydoc.txt named as mydoc.txt.gz and
delete the original file.
Options :
-f option : Sometimes a file cannot be compressed. Perhaps you are trying to compress a
file called “myfile1” but there is already a file called “myfile1.gz”. In this instance, the
“gzip” command won’t ordinarily work.
To force the “gzip” command to do its stuff simply use -f option:
$ gzip -f myfile1.txt

This will forcefully compress a file named myfile.txt even if there already exists a file
named as myfile.txt.gz
-k option :By default when you compress a file using the “gzip” command you end up
with a new file with the extension “.gz”.If you want to compress the file and keep the
original file you have to run the gzip command with -k option:

$ gzip -k mydoc.txt

The above command would end up with a file called “mydoc.txt.gz” and “mydoc.txt”.
-L option : This option displays the gzip license.

$ gzip -L filename.gz

OUTPUT :
Apple gzip 264.50.1 (based on FreeBSD gzip 20111009)
Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green
All rights reserved.
-r option : This option can compress every file in a folder and its subfolders.This option
doesn’t create one file called foldername.gz. Instead, it traverses the directory structure
and compresses each file in that folder structure.

gzip -r testfolder

This will compress all the files present in the testfolder.


-[1-9] option : It allows to change the compression level.A file can be compressed in
different ways. For instance, you can go for a smaller compression which will work
faster or you can go for maximum compression which has the tradeoff of taking longer
to run.The speed and compression level can vary by levels using numbers between 1
and 9.

$ gzip -1 mydoc.txt

This will get maximum compression at the slowest speed

$ gzip -9 mydoc.txt

To get minimum compression at the fastest speed


-v option: This option displays the name and percentage reduction for each file
compressed or decompressed.

$ gzip -v mydoc.txt

OUTPUT :
new.txt: 18.2% -- replaced with new.txt.gz
-d option :This option allows to decompress a file using the “gzip” command.

$ gzip -d mydoc.txt.gz

This command will unzip the compressed file named as mydoc.txt.gz.

gunzip command in Linux with examples

gunzip command is used to compress or expand a file or a list of files in Linux. It


accepts all the files having extension as .gz, .z, _z, -gz, -z , .Z, .taz or.tgz and replace the
compressed file with the original file by default. The files after uncompression retain its
actual extension.
Syntax:
gunzip [Option] [archive name/file name]
Example-1:
To Decompress A File Using The "gunzip" Command:
$ gunzip myfilename.gz
output:
$ ls
myfilename.gz
$ gunzip myfilename.gz
$ ls
myfilename
Example-2:
Force A File To Decompress:
$ gunzip -f myfilename.gz
output:
$ls
myfilename.gz
$ gunzip myfilename.gz
$ls
myfilename
Example-3:
To keep both the compressed and decompressed file:
$ gunzip -k myfile.gz
output:
$ls
myfilename.gz
$ gunzip -k myfilename.gz
$ls
myfilename myfilename.gz
Example-4:
To display compressed output:
$ gunzip -l myfile.gz
output:
$gunzip -l myfilename.gz
compressed uncompressed ratio uncompressed_name
31 0 0.0% myfilename
Example-5:
Decompressing Lots Of Files Recursively:
$ gunzip -r /tmp
output:
$ ls /tmp/
myfilename1.gz myfilename.gz
$ gunzip -r /tmp/
$ ls /tmp/
myfilename myfilename1

zcat Command
Zcat is a command line utility for viewing the contents of a compressed file without
literally uncompressing it. It expands a compressed file to standard output allowing you
to have a look at its contents. In addition, zcat is identical to running gunzip -
c command. In this guide, we will explain zcat command examples for beginners.
1. The first example shows how to view contents of a normal file using cat command,
compress it using gzip command and view the contents of the zipped file using zcat as
shown.

$ cat users.list

$ gzip users.list

$ zcat users.list.gz

2. To view multiple compressed files, use the following command with


filenames as shown.
$ zcat users.list.gz apps.list.gz

3. To view contents of normal files use the -f flag, similar to cat


command, for example.

$ zcat -f users.list

4. To get the properties (compressed size, uncompressed size, ratio


– compression ratio (0.0% if unknown), uncompressed_name
(name of the uncompressed file) of a compressed file, use the -
l flag.

 $ zcat -l users.list.gz
To suppress all warnings, use the -q flag as shown.

$ zcat -q users.list.gz

For more information, see the zcat man page.

$ man zcat

man command in Linux with Examples


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 [OPTION]... [COMMAND NAME]...
Options and Examples
1. No Option: It displays the whole manual of the command.
Syntax :
$ man [COMMAND NAME]
Example:
$ man printf
Output:
In this example, manual pages of the command ‘printf‘ are simply returned.
2. Section-num: Since a manual is divided into multiple sections so this
option is used to display only a specific section of a manual.
Syntax :
$ man [SECTION-NUM] [COMMAND NAME]
Example:
$ man 2 intro
Output:
In this example, the manual pages of command ‘intro‘ are returned which lies
in the section 2.
3. -f option: One may not be able to remember the sections in which a
command is present. So this option gives the section in which the given
command is present.
Syntax:
$ man -f [COMMAND NAME]
Example:
$ man -f ls
Output:
In this example, the command ‘ls‘ is returned with its section number.
4. -a option: This option helps us to display all the available intro manual
pages in succession.
Syntax:
$ man -a [COMMAND NAME]
Example:
$ man -a intro
Output:
In this example you can move through the manual pages(sections) i.e either
reading(by pressing Enter) or skipping(by pressing ctrl+D) or exiting(by
pressing ctrl+C).
5. -k option: This option searches the given command as a regular
expression in all the manuals and it returns the manual pages with the
section number in which it is found.
Syntax:
$ man -k [COMMAND NAME]
Example:
$ man -k cd
Output:
The command ‘cd‘ is searched in all the manual pages by considering it as a
regular expression.
6. -w option: This option returns the location in which the manual page of a
given command is present.
Syntax:
$ man -w [COMMAND NAME]
Example:
$ man -w ls
Output:

The location of command ‘ls‘ is returned.


7. -I option: It considers the command as case sensitive.
Syntax:
$ man -I [COMMAND NAME]
Example:
$ man -I printf
Output:
The command ‘printf‘ is taken as case-sensitive i.e ‘printf‘ returns the manual
pages but ‘Printf‘ gives error.

tar command in Linux with examples


The Linux ‘tar’ stands for tape archive, is used to create Archive and extract the
Archive files. tar command in Linux is one of the important command which provides
archiving functionality in Linux. We can use Linux tar command to create compressed
or uncompressed Archive files and also maintain and modify them.
Syntax:
tar [options] [archive-file] [file or directory to be archived]
Options:
-c : Creates Archive
-x : Extract the archive
-f : creates archive with given filename
-t : displays or lists files in archived file
-u : archives and adds to an existing archive file
-v : Displays Verbose Information
-A : Concatenates the archive files
-z : zip, tells tar command that creates tar file using gzip
-j : filter archive tar file using tbzip
-W : Verify a archive file
-r : update or add file or directory in already existed .tar file

What is an Archive file?


An Archive file is a file that is composed of one or more files along with metadata.
Archive files are used to collect multiple data files together into a single file for easier
portability and storage, or simply to compress files to use less storage space.
Examples:
1. Creating an uncompressed tar Archive using option -cvf : This command creates
a tar file called file.tar which is the Archive of all .c files in current directory.
$ tar cvf file.tar *.c
Output :
os2.c
os3.c
os4.c
2. Extracting files from Archive using option -xvf : This command extracts files from
Archives.
$ tar xvf file.tar
Output :
os2.c
os3.c
os4.c
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 .c files.
$ tar cvzf file.tar.gz *.c
4. Extracting a gzip tar Archive *.tar.gz using option -xvzf : This command extracts
files from tar archived file.tar.gz files.
$ tar xvzf file.tar.gz
5. Creating compressed tar archive file in Linux using option -j : This command
compresses and creates archive file less than the size of the gzip. Both compress and
decompress takes more time then gzip.
$ tar cvfj file.tar.tbz example.cpp
Output :
$tar cvfj file.tar.tbz example.cpp
example.cpp
$tar tvf file.tar.tbz
-rwxrwxrwx root/root 94 2017-09-17 02:47 example.cpp
6. Untar single tar file or specified directory in Linux : This command will Untar a
file in current directory or in a specified directory using -C option.
$ tar xvfj file.tar
or
$ tar xvfj file.tar -C path of file in directory
7. Untar multiple .tar, .tar.gz, .tar.tbz file in Linux : This command will extract or
untar multiple files from the tar, tar.gz and tar.bz2 archive file. For example the above
command will extract “fileA” “fileB” from the archive files.
$ tar xvf file.tar "fileA" "fileB"
or
$ tar zxvf file1.tar.gz "fileA" "fileB"
or
$ tar jxvf file2.tar.tbz "fileA" "fileB"
8. Check size of existing tar, tar.gz, tar.tbz file in Linux : The above command will
display the size of archive file in Kilobytes(KB).
$ tar czf file.tar | wc -c
or
$ tar czf file1.tar.gz | wc -c
or
$ tar czf file2.tar.tbz | wc -c
9. Update existing tar file in Linux
$ tar rvf file.tar *.c
Output :
os1.c
10. list the contents and specify the tarfile using option -tf : This command will list
the entire list of archived file. We can also list for specific content in a tarfile
$ tar tf file.tar
Output :
example.cpp
11. Applying pipe to through ‘grep command’ to find what we are looking
for : This command will list only for the mentioned text or image in grep from archived
file.
$ tar tvf file.tar | grep "text to find"
or
$ tar tvf file.tar | grep "filename.file extension"
12. We can pass a file name as an argument to search a tarfile : This command
views the archived files along with their details.
$ tar tvf file.tar filename
13. Viewing the Archive using option -tvf
$ tar tvf file.tar
Output :
-rwxrwxrwx root/root 191 2017-09-17 02:20 os2.c
-rwxrwxrwx root/root 218 2017-09-17 02:20 os3.c
-rwxrwxrwx root/root 493 2017-09-17 02:20 os4.c

VI EDITOR
The VI editor is the most popular and classic text editor in the Linux family. Below, are
some reasons which make it a widely used editor –

1) It is available in almost all Linux Distributions


2) It works the same across different platforms and Distributions
3) It is user-friendly. Hence, millions of Linux users love it and use it for their editing
needs
vi Command mode:
The vi editor opens in this mode, and it only understands commands
In this mode, you can, move the cursor and cut, copy, paste the text
This mode also saves the changes you have made to the file
Commands are case sensitive. You should use the right letter case.
vi Editor Insert mode:
This mode is for inserting text in the file.
You can switch to the Insert mode from the command mode by pressing ‘i’ on the
keyboard
Once you are in Insert mode, any key would be taken as an input for the file on which you
are currently working.
To return to the command mode and save the changes you have made you need to press
the Esc key
How to use vi editor
To launch the VI Editor -Open the Terminal (CLI) and type
vi <filename_NEW> or <filename_EXISTING>

vi Editing commands
i – Insert at cursor (goes into insert mode)
a – Write after cursor (goes into insert mode)
A – Write at the end of line (goes into insert mode)
ESC – Terminate insert mode
u – Undo last change
U – Undo all changes to the entire line
o – Open a new line (goes into insert mode)
dd – Delete line
3dd – Delete 3 lines.
D – Delete contents of line after the cursor
C – Delete contents of a line after the cursor and insert new text. Press ESC key to end
insertion.
dw – Delete word
4dw – Delete 4 words
cw – Change word
x – Delete character at the cursor
r – Replace character
R – Overwrite characters from cursor onward
s – Substitute one character under cursor continue to insert
S – Substitute entire line and begin to insert at the beginning of the line
~ – Change case of individual character
Note: You should be in the “command mode” to execute these commands. VI editor
is case-sensitive so make sure you type the commands in the right letter-case.
Moving within a file
k – Move cursor up
j – Move cursor down
h – Move cursor left
l – Move cursor right
You need to be in the command mode to move within a file. The default keys for
navigation are mentioned below else; You can also use the arrow keys on the
keyboard.
Saving and Closing the file
Shift+zz – Save the file and quit
:w – Save the file but keep it open
:q – Quit without saving
:wq – Save the file and quit
You should be in the command mode to exit the editor and save changes to the file.

-----------------------end of UNIT – II --------------------------------------------------------------

You might also like