Unit - 1 Linux
Unit - 1 Linux
1.Introduction
1
Introduction
1.3 Why LINUX/UNIX?
• LINUX is free.
• Can view and edit the source code of OS
• It is fully customizable.
• Most Important Feature is Stability
• Important in shared environments and critical applications
• LINUX has better security structure.
• High Portability
• Easy to port new H/W Platform
• Written in C which is highly portable
2
File Handling Utilities
File handling Utilities can be classified in to following categories They
are ,
1) File creating and deleting
2) File naming or renaming
3) Editing files
4) File access permissions
Some times the output may not fit the monitor screen. In such situation you can print
those files in a new file or display the file using less command.
In the above example the output is redirected to new file file3.txt. The cat command will
create new file file3.txt and store the concatenated output into file3.txt.
Commands
Deleting: rm COMMAND:
rm linux command is used to remove/delete the file from the directory.
SYNTAX: $rm [options..] [file | directory]
OPTIONS:
-f Remove all files in a directory without prompting the user.
-i Interactive. With this option, rm prompts for confirmation before
removing any files.
-r (or) –R Recursively remove directories and subdirectories in the
argument list. The directory will be emptied of files and removed. The
user is normally prompted for removal of any write-protected files which
the directory contains. Normally simple rm wont remove directory. Rmdir
removes empty directory.Ex:
$ rm file1
The file1 has been deleted
6
Commands
EXAMPLE: 1) To Remove / Delete a file:
rm file1.txt
Here rm command will remove/delete the file file1.txt.
7
Commands
2) File naming or renaming: Unix support following command for
renaming the file as,
Unix operating system allows the user to edit a file, with the help of
vi editor. The user can append the data, update the existing data by
using different commands of vi editor.
kljdf jfd
Kjgf jhkfg
10
File Handling Utilities
4) File access permissions
Unix file system has three different file access permissions. They are,
The new file can be accessed by any user. These file access permissions
provides security for user files. In file maintaining system owner is the
super user, so he can restrict other users from accessing the files.
Commands
ln COMMAND:
ln command is used to create link to a file (or) directory.
links in UNIX are pointers pointing to a file or a directory. Creating links is a
kind of shortcuts to access a file
SYNTAX: ln [options] existingfile(or directory)name newfile(or
directory)name
Types:
1 sybolic link
2. Hard Link
Symbolic link: it is coated by using –s option. It represents logical file
some where else in the system.
Syntax:
$ ln –s file1 dir1 12
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)
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.
Even if we change the filename of the original file then also the hard links properly
work
Commands
Hard Link : Hard links have same inode number
Syntax
$ ln file1 file2
$ ln sample1 sample2
14
Commands
Unlink COMMAND:
unlink - delete a name and possibly the file it refers to
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set
appropriately.
Syntax
unlink FILE
15
Commands
mkdir COMMAND:
mkdir command is used to create one or more directories.
SYNTAX: mkdir [options] directories
OPTIONS:
-m Set the access mode for the new directories.
-p Create intervening parent directories if they don't exist.
-v Print help message for each directory created.
EXAMPLE:
1. Create directory:
mkdir test
The above command is used to create the directory 'test'.
2. Create directory and set permissions:
mkdir -m 666 test
The above command is used to create the directory 'test' and set the read
16
and write permission.
3 . -p : Create intervening parent directories if they don't
exist.
cp COMMAND:
cp command copy files from one location to another. If the destination is an
existing file, then the file is overwritten; if the destination is an existing
directory, the file is copied into the directory (the directory is not
overwritten). SYNTAX: $cp [OPTIONS]... SOURCE DEST
cp [OPTIONS]... SOURCE... DIRECTORY
cp [OPTIONS]... --target-directory=DIRECTORY SOURCE...
OPTIONS:
--a same as -dpR.
--backup[=CONTROL] make a backup of each existing destination file
-b like --backup but does not accept an argument.
-f if an existing destination file cannot be opened, remove it and try
19
Commands
Ulimit COMMAND:
Ulimit stands for user limit.
Ulimit gives a value as an output, which specifies the largest file that can be
created by the user in the file system.
Syntax:
$ ulimit
3045678
The output value represents that user can’t create a file which is bigger than
3045678 bytes.
Find COMMAND:
Find command recursively check’s the directory tree to find out the given files
either by name or by matching one or more file attributes.
Syntax:
20
Find path list selection_criteria action
Commands
Find /oracle -name temp -print
/oracle - path list
-name temp- selection_criteria
-print action
Example1: find all the files in /home with name test.txt. Here –name is used
to specify the filename.
find /home –name test.txt
Example2: find the files whose name is test.txt and in present working
directory
find . –name test.txt Or
find –name test.txt
Example3: find all the files whose name contains both capital letters and
small letters in it.
21
find /home –iname test.txt
Commands
Example4:Search for a file name test.txt and its permissions are 775 in a
given box
find / -perm 775 –name test.txt
Example5: How about searcing files with SUID bit set and file permissions are
755?
find / -perm 4755
Example6: Search for all the files with name test.txt and the owner of this file
is amar
find / -user Surendra –name test.txt
Example7: find all the files whos name is test.txt and owned by a group
called redcluster
find / -group redcluster –name test.txt
22
Commands
Pwd COMMAND:
Short for print working directory the pwd command displays the name of the
current working directory.
Syntax
pwd
Examples
pwd
Typing pwd at the prompt would give you something similar to:
/home/computerhope/public_html
23
Security by file permissions
File ownership is an important component of UNIX that provides a secure
method for storing files. Every file in UNIX has the following attributes:
Owner permissions: The owner's permissions determine what actions the
owner of the file can perform on the file.
Group permissions: The group's permissions determine what actions a
user, who is a member of the group that a file belongs to, can perform on the
file.
Other (world) permissions: The permissions for others indicate what
action all other users can perform on the file.
The Permission Indicators:
While using ls -l command it displays various information related to file
permission as follows:
$ls -l
-rwxr-xr-- 1 root users 1024 Nov 2 00:10 myfile 24
24
Security by file permissions
File Access Modes:
The permissions of a file are the first line of defense in the security of a Unix
system. The basic building blocks of Unix permissions are the read, write,
and execute permissions, which are described below:
Read: Grants the capability to read ie. view the contents of the file.
Write: Grants the capability to modify, or remove the content of the file.
Execute: User with execute permissions can run a file as a program
Changing Permissions:
To change file or directory permissions, you use the chmod (change mode)
command. There are two ways to use chmod: symbolic mode and absolute
mode.
Using chmod in Symbolic Mode:
The easiest way for a beginner to modify file or directory permissions is to
use the symbolic mode. With symbolic permissions you can add, delete, 25
or
Security by file permissions
Chmod operator Description
+ Adds the designated permission(s) to a file or directory.
- Removes the designated permission(s) from a file or
directory.
= Sets the designated permission(s).
Here's an example using testfile. Running ls -1 on testfile shows that the file's
permissions are as follows:
$ ls -l testfile
27
Security by file permissions
Here's how you could combine these commands on a single line:
28
Security by file permissions
Number Octal Permission Representation Ref
0 No permission ---
1 Execute permission --x
2 Write permission -w-
3 Execute and write permission: 1 (execute) + 2 (write) = 3 -wx
4 Read permission r--
5 Read and execute permission: 4 (read) + 1 (execute) = 5 r-x
6 Read and write permission: 4 (read) + 2 (write) = 6 rw-
7 All permissions: 4 (read) + 2 (write) + 1 (execute) = 7 rwx
29
Security by file permissions
Here's an example using testfile. Running ls -1 on testfile shows that the file's
permissions are as follows:
$ls -l testfile
-rwxrwxr-- 1 root users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on
testfile, followed by ls -l so you can see the permission changes:
$ chmod 755 testfile
$ls -l testfile
-rwxr-xr-x 1 root users 1024 Nov 2 00:10 testfile
$chmod 743 testfile
$ls -l testfile
-rwxr---wx 1 root users 1024 Nov 2 00:10 testfile
$chmod 043 testfile
$ls -l testfile 30
Security by file permissions
Changing Owners and Groups:
While creating an account on Unix, it assigns a owner ID and a group ID to
each user. All the permissions mentioned above are also assigned based on
Owner and Groups.
Two commands are available to change the owner and the group of files:
chown: The chown command stands for "change owner" and is used to
change the owner of a file.
chgrp: The chgrp command stands for "change group" and is used to change
the group of file.
Changing Ownership:
The chown command changes the ownership of a file. The basic syntax is as
follows:
$ chown user filelist
The value of user can be either the name of a user on the system or the user
id (uid) of a user on the system.
Following example:
$ chown root1 testfile
Changes the owner of the given file to the user root1
NOTE: The super user, root, has the unrestricted capability to change the
ownership of a any file but normal users can change only the owner of files
they own. 31
Security by file permissions
• Changing Group Ownership:
• The chrgp command changes the group ownership of a file. The basic
syntax is as follows:
• $ chgrp group filelist The value of group can be the name of a group on
the system or the group ID (GID) of a group on the system.
• Following example:
• $ chgrp special testfile
• Changes the group of the given file to special group.
32
Process utilities
ps COMMAND:
ps command is used to report the process status. ps is the short name for
Process Status.
SYNTAX: The Syntax is ps [options]
OPTIONS:
-e List information about every process now running.
-f Generates a full listing.
–u option followed by user-id displays the processes owned by
the user-id.
-l Generate a long listing.
34
Process utilities
who COMMAND:
who command can list the names of users currently logged in, their terminal,
the time they have been logged in, and the name of the host from which they
have logged in.
SYNTAX: who [options] [file]
OPTIONS:
-H Print column headings above the output.
-u provides a detailed list
EXAMPLE:
1. who -uH
Output:
NAME LINE TIME IDLE PID COMMENT
hiox ttyp3 Jul 10 11:08 . 4578
This sample output was produced at 11 a.m. The "." indicates activity within
the last minute. 35
Process utilities
who am i
who am i command prints the user name.
w command:
w - show who is logged on and what they are doing
DESCRIPTION
w displays information about the users currently on the machine, and their
processes. The header shows, in this order, the current time, how long the
system has been running, how many users are currently logged on, and the
system load averages for the past 1, 5, and 15 minutes.
Kill COMMAND:
• To terminate the running process
Kill command in UNIX and Linux is normally used to kill a suspended or hanged
process or process group.
Example: 36
Process utilities
The following example shows how to kill a process,
Kill 19426 This will kill the process ora with PID 19426
To terminate more than one process at a time, use the following syntax
In kill utility we will give PID where as in pkill utility we have to give the
name of the process
kill -9 is used to forcefully terminate a process in Unix. Here is syntax of
kill command in UNIX.
ps -ef| grep process_identifier // will give you PID
kill -9 PID
37
Job Control:
Lets simultaneously run a few commands that takes some time to complete.
Here we have executed 4 sleep commands and all are started in the background
as denoted by &.
$ jobs
$ fg %job-number
To bring job number 2 to the foreground, you run the following command.
$ fg %2
To suspend a job, you first bring the job to the foreground and then press the
keys Ctrl + z.
Alternately, you can also suspend a job running in the background as follows.
$ stop %job-number
Send a job to the background
$ bg %job-number
To resume the suspended job 2 in the background, you can run the following command.
$ bg %2
$ jobs –r
$ jobs –s
Terminate a job
To terminate a job, you first bring the running job to the foreground, and then press the keys Ctrl +
c.
You can also terminate a job without bringing it in the foreground just by passing the job number to
kill.
$ kill %job-number
$ kill %3
Top command :
This utility tells the user about all the running processes on the Linux machine.
Syntax: $ top
Field Description Example 1 Example 2
PID The process ID of each task 1525 961
To start a process with a niceness value other than the default value use the
following syntax
The name nohup stands for "no hangup." The hangup (HUP) signal, which is
normally sent to a process to inform it that the user has logged off (or "hung
up"), is intercepted by nohup, allowing the process to continue running.
46
• If you want the above information in a readable format, then use the
command
$ df –h
Free :
This command shows the free and used memory (RAM) on the
Linux system.
• You can use the arguments
• free -m to display output in MB
• free -g to display output in GB
Disk utilities
Du COMMAND:
The du command displays the disk space used by the specified files and
directories.
Syntax:
du [option]….[file]
Options:
1) –a: it writes counts for all files, not just for directories .
2) -b: it prints the size in bytes.
3) -c: it prints the grand total (i.e, the total disk space used by the directory).
4) -h: it prints the human readable formats.example1k,2g
5) -s: it does not show the size of sub-directories.
[mamta@localhost ~]$ du -a
8 ./.zshrc
8 ./f1
8 ./.bashrc
8 ./.kde/Autostart/.directory
48
16 ./.kde/Autostart
To see the file size
$ du –sh new.tar
12k new.tar
to compress the tar file use gzip
$ gzip –v new.tar
$ ls
new.tar.gz
4.0k new.tar.gz
Networking commands
The commands which we will use for the communication between more than
one system for sharing resources or any other issue are known as the
networking commands.
Commands such as telnet, ftp, rlogin, finger are commonly used networking
commands.
telnet COMMAND:
telnet is a internet protocol which enables user to connect a remote system
and
transfer data.
Syntax: $ telnet hostname or telnet ip_address
Example : $ telnet itctnss0123
Trying 164.130….
Connected to itctnss0123.
Escape character is ‘^]’.
SunOS 5.8
login: root
Password:
50
Last login: Thu Feb 24 16:13:12 from itctnss0123
Networking commands
Finger COMMAND:
The finger command is used to find out the details of a user, on both local
and remote system.
Finger may be disabled on other systems for security reasons.
Following are the simple syntax to use finger command:
Check all the logged in users on local machine as follows:
Examples:
[amar@localhost ~]$ finger
Login Name Tty Idle Login Time Office Office Phone
amar pts/1 May 25 10:06 (172.16.10.5)
root root pts/0 7d May 16 14:03 (:0.0)
program allows a user to transfer files to and from a remote network site.
This utility helps you to upload and download your file from one computer to
another computer.
The ftp utility has its own set of UNIX like commands which allow you to
Navigate directories.
55
Filters
cat COMMAND:
cat linux command concatenates files and print it on the standard output.
SYNTAX: $ cat [OPTIONS] [FILE]...
OPTIONS:
-A Show all.
-b Omits line numbers for blank space in the output.
-e A $ character will be printed at the end of each line prior to a new
line.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
-s If the output has multiple empty lines it replaces it with one empty
line.
-T Displays the tab characters in the output.
-v Non-printing characters (with the exception of tabs, new-lines and
form-feeds) are printed visibly.
Examples:
In the above example the output is redirected to new file file3.txt. The cat
command will create new file file3.txt and store the concatenated output into
file3.txt.
head COMMAND:
head command is used to display the first ten lines of a file, and also
specifies
how many lines to display
58
Filters
OPTIONS:
-n To specify how many lines you want to display.
-n number The number option-argument must be a decimal integer
whose sign affects the location in the file, measured in lines.
EXAMPLE:
1. head f1.txt
This command prints the first 10 lines of ' f1.txt '.
2. head -5 f1.txt
The head command displays the first 5 lines of ' f1.txt '.
3. head -c 5 f1.txt
The above command displays the first 5 characters of ' f1.txt '.
60
-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
-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.
SYNTAX:
$ tail [options] filename
OPTIONS:
-b To specify the units of blocks.
-n To specify how many lines you want to display.
-c number The number option-argument must be a decimal integer
whose sign affects the location in the file, measured in bytes.
-n number The number option-argument must be a decimal integer
whose sign affects the location in the file, measured in lines.
62
EXAMPLE:
1. tail index.php
It displays the last 10 lines of 'index.php'.
2. tail -2 index.php
It displays the last 2 lines of 'index.php'.
3. tail -n 5 index.php
It displays the last 5 lines of 'index.php'.
4. tail -c 5 index.php
It displays the last 5 characters of 'index.php'.
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.
/mam123 $ cat hii
hii
how r u
EXAMPLE:
1. cut -c1-3 text.txt
Output:
Thi
Cut the first three letters from the above line.
2. cut -d, -f1,2 text.txt
Output:
This is, an example program
The above command is used to split the fields using delimiter and cut the
first two fields.
65
mam123$ cat hii
hii
how r u
f
b
snist@snist-HP-Compaq-4000-Pro-SFF-PC:~/mam123$ cut -c2 hii
i
o
i
y
snist@snist-HP-Compaq-4000-Pro-SFF-PC:~/mam123$ cut -c -2 hii
hi
ho
fi
by
$ cut -b -3 state.txt
And
Aru
Ass
Bih
Chh
-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.
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 C
If -d option is used then it considered space as a field separator or delimiter:
Andhra
Arunachal
Assam
Bihar
Chhattisgarh
Command prints field from first to fourth of each line from the file. Command:
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Filters
paste COMMAND:
paste command is used to paste the content from one file to another file. It is
also used to set column format for each line.
Paste command is one of the useful commands in Unix or Linux operating system. It is
used to join files horizontally (parallel merging) by outputting lines consisting of lines
from each file specified, separated by tab as delimiter, to the standard output.
SYNTAX:
$ paste [options] [FILES]...
OPTIONS:
-s Paste one file at a time instead of in parallel.
-d Reuse characters from LIST instead of TABs .
EXAMPLE:
1. paste test.txt>test1.txt
Paste the content from 'test.txt' file to 'test1.txt' file.
2. ls | paste - - - -
List all files and directories in four columns for each line.
71
$ cat numbers
1
2
3
4
5
$ cat state
Arunachal Pradesh
Assam
Andhra Pradesh
Bihar
Chhattisgrah
$ cat capital
Tanagar
Dispur
Hyderabad
Patna
Raipur
1|Arunachal Pradesh|Itanagar
2|Assam|Dispur
3|Andhra Pradesh|Hyderabad
4|Bihar|Patna
5|Chhattisgrah|Raipur
In the above command, first it reads data from number file and merge
them into single line with each line separated by tab. After that newline
character is introduced and reading from next file i.e. state starts and
process repeats again till all files are read.
Combination of -d and -s:
1:2:3:4:5
Arunachal Pradesh:Assam:Andhra Pradesh:Bihar:Chhattisgrah
Itanagar:Dispur:Hyderabad:Patna:Raipur
sort COMMAND:
sort command is used to sort the lines in a text file.
SORT command sorts the contents of a text file, line by line.
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.
SYNTAX:
Sort [options] filename
OPTIONS:
-r Sorts in reverse order.
-u If line is duplicated display only once.
-o filename Sends sorted output to a file.
$ cat > file.txt
abhishek
chitransh
satish
Rajan
naveen
divyam
harsh
$ sort file.txt
Output :
abhishek
chitransh
divyam
harsh
naveen
rajan
satish
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 lower case letters
would be sorted following with the upper case letters .
Example:
Create a file mix.txt
$ sort mix.txt
abc
Abc
apple
Bat
BALL
-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.
Syntax :
$ sort inputfile.txt > filename.txt
$ sort -o filename.txt inputfile.txt
Ex:
$ sort file.txt > output.txt
$ sort -o output.txt file.txt
$ cat output.txt
abhishek
chitransh
Divyam
harsh
naveen
rajan
satish
Filters
tr COMMAND:
• tr filter translates specified characters into other characters.
Syntax:
tr [options] string1 string2
Options
-c : complements the set of characters in string.i.e., operations apply to
characters not in the given set
-d : delete characters in the first set from the output.
-s : replaces repeated characters listed in the set1 with single occurrence
• Translates any character read from stdin that is in string1 into the
corresponding character from string2; otherwise the character is
simply passed through.
• string1 and string2 normally have the same number of characters.
• Eg tr abc X5Z 80
translates a into X, b into 5 and c into Z.
$ cat > f1
a
B
C
D
E
F
G
H
i
$ cat f1 | tr ‘a-i’ ‘1-9’
o/p:
o/p :
xelcome to linux
How to convert lower case to upper case
(OR)
$cat SORT123 | tr “[:lower:]” “[:upper:]”
Output:
elcome To LINUX
Output:
my ID is
How to complement the sets using -c option
You can complement the SET1 using -c option. For example, to remove
all characters except digits, you can use the following.
Output:
73535
-s (option ) : : Replaces repeated characters listed in the set1 with single
occurrence
$ cat > f2
welcome to linux programming
Linux programming is interesting
Linux is an operation syster
$ cat f2 | tr –s [+m]
o/p:
$ cat f2 | tr –s ‘[:blank:] ‘
o/p:
Filters
uniq COMMAND:
• uniq assumes lines of ASCII file are sorted and deals with unique lines
depending on the option given.
• No option, one copy of each unique line is printed to stdout. Duplicated
lines are discarded.
Eg $ uniq dups
dups: default output:
A a
b b
b c
c dd
dd ddd
ddd
ddd
Ddd
Eg uniq -d dups
output:
a b
b ddd
b
c
dd
ddd
ddd
ddd
uniq runs as filter or as program driving a pipeline.
There are options to compare fields and to count duplicated lines.
87
Filters
Wc COMMAND:
The purpose of wc command is to count the number of lines,words,characters
in a particular file or files
Syntax: $ wc filename
Example:
$ wc file1
5 40 200 file1
First column represents number of lines
Second column represents number of words
Third column represents number of charcters
Fourth column shows the file name
OPTIONS:
-l (line)
-w (words) 88
Filters
cmp COMMAND:
Compares two files and tells you what line numbers are different.
By default location of first mismatch is displayed
Syntax: $ cmp [-options] filename1 filename2
-l this option displays the list of all differences present in the file byte-
by-byte.
-s Write nothing for differing files; return exit status(‘0’ or ‘1’) only.
the ‘0’ specifies that two files are similar and ‘1’ specifies that there
is at least one that is different.
89
Text processing utilities
• The operations performed by the text processing utilities are as follows
91
Text processing utilities
head:
head command as the name implies, displays the top of the file. When used
without an option, it displays the first 10 lines of the file.
$head file
We can use –n option to specify a line count and display, say first 3 lines of
the file.
$head –n 3 file or $head -3 file
Sort:
Sort can be used for sorting the contents of a file.
$sort shortlist
Sorting starts with the first character of each line and proceeds to the next
character only when the characters in two lines are identical.
Sort options:
With –t option sorts a file based on the fields. 51
Text processing utilities
52
Text processing utilities
nl:
nl is used for numbering lines of a file.
Nl numbers only logical lines –those containing something other apart from
the new line character.
$nl file
nl uses a tab as a default delimiter, but we can change it with –s option.
$nl –s: file
nl won’t number a line if it contains nothing.
53
Grep: globally search for a regular expression and print.
Grep scans a file for the occurrence of a pattern and depending
on the options used, displays
Lines containing the selected
pattern.
Lines not containing the selected
pattern (-v).
Line numbers where pattern
occurs (-n)
No. of lines containing the
pattern (-c)
File names where pattern occurs (-l)
Syntax:
grep option pattern filename(s)
$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.
o/p
-c : Displaying the count of number of matches : We can find the number of
lines that matches the given string/pattern
Output:
-l : 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
-o : 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.
Output:
unix
unix
unix
unix
-n : Show line number while displaying the output using grep -n : To show
the line number of file with the line matched.
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.
-v : Inverting the pattern match : You can display the lines that are not
matched with the specified search sting pattern using the -v option.
Output:
learn operating system. Unix linux which one you choose.
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.
Output:
unix is great os. unix is opensource. unix is free os.
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.
101
Search for Specific Characters :
The following example searches for either J, or N, or R.
(or)
this searches for the string strcpy in all files in the current directory with names
ending in the .c character string.
To display the names of files that contain a pattern:
This searches the files in the current directory that end with .cand displays the
names of those files that contain the strcpy string.
Text processing utilities
• Cut: slitting the file vertically
Cutting fields:
107
Text processing utilities
Ex:
$cat file1.txt
1 AAYUSH
2 APAAR
3 HEMANT
4 KARTIK
// by default join command takes the first column as the key to join as in the
above case //
using -a FILENUM option : Now, sometimes it is possible that one of the files
contain extra fields so what join command does in that case is that by default, it
only prints pairable lines. For example, even if file file1.txt contains an extra
field provided that the contents of file2.txt are same then the output produced by
join command would be same:
$cat file1.txt
1 AAYUSH
2 APAAR
3 HEMANT
4 KARTIK
5 DEEPAK
//displaying contents of file2.txt//
$cat file2.txt
1 101
2 102
3 103
4 104
$join file1.txt file2.txt
1 AAYUSH 101
2 APAAR 102
HEMANT 103
4 KARTIK 104
// although file1.txt has extra field the output is not affected cause the 5 column in
file1.txt was unpairable with any in file2.txt//
/using join with -a option// //1 is used with -a to display the contents of first file passed//
1 AAYUSH 101
2 APAAR 102
3 HEMANT 103
4 KARTIK 104
5 DEEPAK
using -v option : Now, in case you only want to print unpairable
lines i.e suppress the paired lines in output then -v option is used with
join command.
5 DEEPAK
using -1, -2 and -j option : As we already know that join combines lines
of files on a common field, which is first field by default.However, it is not
necessary that the common key in the both files always be the first
column.join command provides options if the common key is other than
the first column.
• The -1 and -2 here represents he first and second file and these
options requires a numeric argument that refers to the joining field for
the corresponding file.
• $cat file1.txt
AAYUSH 1
APAAR 2
HEMANT 3
KARTIK 4
cat file2.txt
101 1
102 2
103 3
104 4
//here -1 2 refers to the use of 2 column of first file as the common field
and -2 2 refers to the use of 2 column of second file as the common field
Back up utilities
The two back up utilities are used in Linux. They are,
1) Cpio
2) Tar
115
$ ls | cpio -ov > archive.cpio
$ ls
$ mkdir dir12
$ cd dir12
dir12$ touch f1 f2 f3 f4 f5 f6
$ ls
Dir123.tar
$ du –sh dir123.tar
120k dir123
$ gzip dir123.tar
To compress tar.gz file use bzip2
$ bzip2 –v dir123.tar.gz
$ dir123.tar.gz.bz2
$bunzip –v dir123.tar.gz.bz2
To extract gz files
$gunzip –v dir123.tar.gz
Dir123.tar
62
Sed
Options:
-e: it is a default option. It indicates that the script is on the command line.
-f: it indicates that script is in a file which immediately follows this option.
-n: it suppresses the automatic output. That is, it will not display the contents
of the pattern space.
62
Scripts, Operation
A script is nothing more than a file of commands or instructions.
Each command consists of an address and an action, where the address can
be a pattern (regular expression)
address ! Action
Complement operator(optional)
A Sed instruction
61
Scripts
Here is an example of sed script namely sample.sed
Sample.sed
# this is one line comment
#this is another comment
3d
1,10s/friends/buddies/
In the sample script, the first two line are the comments. The third and
fourth lines are the instructions. The former specifies the third line in the
input file is to be deleted while the later specifies to replace all occurrences
of “friends” by “buddies ” in the input lines 1 through 10.
61
Scripts, Operation
As each line of the input file is read, sed reads the first command of the script
and checks the address or pattern against the current input line
If there is a match, the command is executed
If there is no match, the command is ignored
61
Addresses
Address determines which lines in the input file are to be processed by
the command(s)
if no address is specified, then the command is applied to each input
line
Address types:
• Single-Line address
• Set-of-Lines address
• Range address
• Nested address
Single-Line Address
• Specifies only one line in the input file
• special: dollar sign ($) denotes last line of input file
66
Addresses
Examples:
• show only line 3
sed -n -e '3 p' input-file
• show only last line
sed -n -e '$ p' input-file
• substitute ―”endif” with ―”fi” on line 10
sed -e '10 s/endif/fi/' input-file
Set-of-Lines Address
• use regular expression to match lines
• written between two slashes
• process only lines that match
• may match several lines
• lines may or may not be consecutives
Examples:
• /^A/command (Matches all lines that start with ‘A’)
• /^$/colmmand (Matches blank lines)
67
Addresses
Range Address
• Defines a set of consecutive lines
Format:
• start-addr,end-addr (inclusive)
following are the possible combinations
• 10,50 line-number,line-number
• 10,/R.E/ line-number,/RegExp/
• /R.E./,10 / RegExp/,line-number
• /R.E./,/R.E/ /RegExp/,/RegExp/
Examples :
4,9 (Matches all lines 4 through 9)
2,/^A/command (starts matching from line 2 to a line that starts with A)
/^A/,15 (starts matching from a line that begins with A to 15)
/^A/,/$B/command (starts matching from a line that begins with A to a line
that ends with B)
68
• $ sed –n ‘3-6p’ f1.txt
Example:
To delete all blank lines between line 11 and 20 the instruction is as follows
11,20,{
/^$/ d
}
• To delete all the lines that contain the word “Happy” as well as “life” is as
follows
/Happy/ {
/life/d
}
• print lines that do not contain “obsolete” 69
Commands
Line Number
line number command (=) writes the current line number before each
matched/output line
Example:
70
sed ‘=’ command accepts only one address, so if you want to print line number for a range of lines,
you must use the curly braces.
Syntax:
# sed -n '/PATTERN/,/PATTERN/ {
=
p
}' filename
• Print the line numbers for the lines matches from the pattern “Oracle” to “Productivity”.
$ sed -n '/Oracle/,/Productivity/{
=
p
}' f1.txt
o/p:
2
Databases - Oracle, mySQL etc.
3
Security (Firewall, Network, Online Security etc)
4
Storage in Linux
5
Productivity (Too many technologies to explore, not much time available)
• Find the line number which contains the pattern
• The below sed command prints the line number for which matches
with the pattern “Databases”
o/p :
2
6
Commands
Insert Command: I
• adds one or more lines directly to the output before the address:
• inserted “text” never appears in sed‘s pattern space
• cannot be used with a range address; can only be used with the single-
line and set-of-lines address types
Syntax:
• [address] i\
text \ 71
1. Add a line before the 4th line of the line:
Linux Sysadmin
Databases - Oracle, mySQL etc.
Security (Firewall, Network, Online Security etc)
Cool gadgets and websites
Storage in Linux
Productivity (Too many technologies to explore, not much time available)
Windows- Sysadmin, reboot etc.
2. Insert a line before every line with the pattern
o/p :
Linux Scripting
Linux Sysadmin
Databases - Oracle, mySQL etc.
Security (Firewall, Network, Online Security etc)
Storage in Linux
Productivity (Too many technologies to explore, not much time available)
Linux Scripting
Windows- Sysadmin, reboot etc.
3. Insert a line before the last line of the file.
Insert a line “Website Design” before the last line of the file.
o/p :
Script.sed
$a\
Is it difficult? Try again!
72
Addresses
Change Command: c
• replaces the lines matching the address with x:new text
• accepts four address types:
• single-line, set-of-line, range, and nested addresses.
Syntax:
• [address1[,address2]] c\
text
Ex: $sed –f script.sed twister.dat
Script.sed
5c\
Red Blood Blue Blood\
Deadly Dinosaurs Danced Dizzly
o/p:
Delete Command:
Syntax:
[address1[,address2]] d
73
Commands
Ex: to delete all the lines that starts with a capital letter either B or I
o/p:
73
Commands
Substitute command:
The substitute command, replaces the text matching the search pattern with
a replacement string.
Syntax:
• [address(es)]s/pattern/replacement/[flags]
– pattern - search pattern
79
Commands
sed i/o commands :
1.Next:
The next command, n reads the next line from the input file into the pattern
space. before reading the next line , it sends the current contents of the
pattern space to the standard output, deletes the current line in it and
then copies the next line
Ex:the command to delete a blank line if it appears after a line that starts
with a digit is given below
80
Commands
Myscript.sed
/^[0-9]/{
/^$/d
2 .Append Next(N):
• The append next command, adds the next input line to the current
contents of the pattern space
• This command is useful when applying patterns to two or more lines at the
same time.
• Ex : the command to append next line to the current line if the current
line ends with a colon(:) 81
Commands
Script.sed
/:$/N
s/\n/ /
3.Print(p)
The Print command (p) prints the current content of the pattern space to
standard otput, useful if the -n option has been specified
• Syntax: [address1[,address2]]p
• Note: if the –n option has not been specified, p will cause the line to be
output twice!
• Examples:
It prints only the first line of the pattern space. it stops print when it finds a
new line character.
List Command
5.List(l)
Ex:
83
Commands
Out put:
\t another tab.$
File commands
• allows to read and write from/to file while processing standard input
• read: r command
• write: w command
Ex: write the command to insert the content of file2.txt before the contents
of file1.txt
84
$ sed ‘ 1r file2.txt ’ file1.txt
Commands
Ex: write the command to save first 20 lines from file1.txt to a file output.txt
Quit
• Quit causes sed to stop reading new input lines and stop sending them to
standard output
• It takes at most a single line address
– Once a line matching the address is reached, the script will be
terminated
– This can be used to save time when you only want to process some
portion of the beginning of a file
• Example: to print the first 100 lines of a file (like head) use:
– sed '100q' filename
– sed will, by default, send the first 100 lines of filename to standard85
Awk
The awk utility, which takes its name from the initials of its authors (Aho,
Weinberger, and Kernighan), is a powerful programming language.
86
Execution
In addition to input data, awk also requires one or more instructions that
provide editing instructions.
A few instructions can be entered at the command line from the keyboard.
Most of the time, the instructions are placed in a file known as an awk
script.
Syntax
Options
-f: it indicates that script is in a file which immediately follows this option.
Ex:
87
$awk –F “\t” –f firstscript.awk info.dat
Fields and Records
The awk utility views a file as a collection of fields and records.
88
A Data File
89
Field Buffers
There are as many field buffers available as there are fields in the current
record of the input file.
Each buffer has a name, which is the dollar sign $ followed by the field
number in the current record.
90
Record Buffer
91
System Variables
92
System Variables
Examples :
% cat emps
Tom Jones 4424 5/12/66 543354
Mary Adams 5346 11/4/63 28765
Sally Chang 1654 7/22/54 650000
Billy Black 1683 9/23/44 336500
93
Recursive representation
awk Script of Factorial(4)
• BEGIN: pre-processing
• performs processing that must be completed before the file processing
starts (i.e., before awk starts reading records from the input file)
• useful for initialization tasks such as to initialize variables and to create
report headings
• BODY: Processing
• contains main processing logic to be applied to input records
• if a file contains 100 records, the body will be executed 100 times,
one for each record
94
awk Script
• END: post-processing
• contains logic to be executed after all input data have been
processed
• logic such as printing report grand total should be performed in
this part of the script
95
Operations
• The awk utility reads an input file, line by line and applies all the
instructions in awk script to each input line. It does not print the lines
unless the print action is specified .consider a records .dat with five fields
i.e,s.no,name,test1,test2,test3 and four records.
1 A 75 81 89
2 B 86 94 82
3 C 90 71 96
4 D 82 70 85
Total.awk
#initialization section
#body section
{total=$3+$4+$5}
#END of job
Output:
Name total
A 245
B 262
C 257
D 237
Best Result 97
Pattern/Action
suma 98
Expression Pattern types
• match
– entire input record
• expression operators
– arithmetic
– relational
– logical
99
Example: match input record
% cat employees2
Tom Jones:4424:5/12/66:543354
Mary Adams:5346:11/4/63:28765
Sally Chang:1654:7/22/54:650000
Billy Black:1683:9/23/44:336500
Sally Chang:1654:7/22/54:650000
Billy Black:1683:9/23/44:336500
100
Arithmetic Operators
Operator Meaning Example
+ Add x+y
- Subtract x–y
* Multiply x*y
/ Divide x/y
% Modulus x%y
^ Exponential x^y
Example:
103
Relational Operators
Operator Meaning Example
== Equal to x == y
!= Not equal to x != y
104
Logical Operators
Operator Meaning Example
|| Logical OR a || b
! NOT !a
Examples:
105
Logical Operators
Operator Meaning Example
|| Logical OR a || b
! NOT !a
Examples:
105
Range Patterns
Matches ranges of consecutive input lines
Syntax:
Example:
106
awk Actions
• The first job of a preprocessor is file inclusion - the copying of one or
more files into programs.
#include filename
1. #include <filename>
2. #include “filename”
107
awk expressions
Expression is evaluated and returns value
consists of any combination of numeric and string constants,
variables, operators, functions, and regular expressions
As target of assignment
108
awk variables
• A user can define any number of variables within an awk script
• The variables can be numbers, strings, or arrays
• Variable names start with a letter, followed by letters, digits, and
underscore
• Variables come into existence the first time they are referenced; therefore,
they do not need to be declared before use
• All variables are initially created as strings and initialized to a null string “”
Format:
variable = expression
Examples:
% awk '$1 ~ /Tom/
{wage = $3 * $4; print wage}'
filename
% awk '$4 == "CA"
{$4 = "California"; print $0}' 109
filename
awk assignment operators
= assign result of right-hand-side expression to
left-hand-side variable
++ Add 1 to variable
173
Output Statements
print
printf
sprintf
174
Awk control structures
• Conditional
• if-else
• Repetition
• for
• with counter
• with array index
• while
• do-while
175
if Statement
Syntax:
if (conditional expression)
statement-1
else
statement-2
Example:
if ( NR < 3 )
print $2
else
print $3
176
for Loop
Syntax:
for (initialization; limit-test; update)
statement
Example:
for (i = 1; i <= NR; i++)
{
total += $i
count++
}
• For loop for arrays
Syntax:
for (var in array)
statement
Example:
for (x in deptSales)
{
print x, deptSales[x] } 177
while Loop
Syntax:
statement
Example:
i=1
print i, $i
i++
178
do-while Loop
Syntax:
do
statement
while (condition)
• statement is executed at least once, even if condition is false at the
beginning
Example:
i=1
do {
print $0
i++