6 BCA BBA Linux Commands
6 BCA BBA Linux Commands
1
date
date command is helpful to display date in several formats. It also
allows you to set systems date and time.
1.date command without any option will display the current date and
time.
$ date
Mon May 20 22:02:24 PDT 2013
2.date command with -d or –date option will convert the input string
into date format.
$ date --date="12/2/2014" Note:
Tue Dec 2 00:00:00 PST 2014 Pacific Daylight Time (PDT) is 7 hours
behind Coordinated Universal Time
$ date --date="2 Feb 2014"
(UTC)
Sun Feb 2 00:00:00 PST 2014 Pacific Standard Time (PST) is 8 hours
$ date --date="Feb 2 2014" behind Coordinated Universal Time
Sun Feb 2 00:00:00 PST 2014 (UTC)
$ date --date="Feb 2 2014 13:12:10"
Sun Feb 2 13:12:10 PST 2014
2
date
3. Get Relative Date Using –date option to get a future date using
relative values.
$ date --date="next mon"
Mon May 27 00:00:00 PDT 2013
4
date
6. Various Date Command Formats
The following formatting option is to display date command in various
formats using the following syntax:
Format
Purpose of Option Output
options
date +%a Displays Weekday name in short (like Mon, Tue, Wed) Thu
Displays Weekday name in full short (like Monday,
date +%A Thursday
Tuesday)
date +%b Displays Month name in short (like Jan, Feb, Mar ) Feb
date +%B Displays Month name in full short (like January, February) February
date +%d Displays Day of month (e.g., 01) 07
date +%D Displays Current Date; shown in MM/DD/YY 02/07/13
date +%F Displays Date; shown in YYYY-MM-DD 2013-02-07
date +%H Displays hour in (00..23) format 23
date +%I Displays hour (01..12) format 11
date +%j Displays day of year (001..366) 038
date +%m Displays month (01..12) 02
5
date
Various Date Command Formats
Format
Purpose of Option Output
options
date +%M Displays minute (00..59) 44
date +%S Displays second (00..60) 17
date +%N Displays nanoseconds (000000000..999999999) 573587606
Displays time; shown as HH:MM:SS. Note: Hours in 24
date +%T 23:44:17
Format
date +%u Displays day of week (1..7); 1 is Monday 4
Displays week number of year, with Sunday as first day of
date +%U 05
week (00..53)
date +%Y Displays full year i.e. YYYY 2013
date +%Z alphabetic time zone abbreviation (e.g., EDT) IS
6
time
Linux time command is helpful to identify the time taken by a command.
Using Linux time command, you can figure out how much time was
taken to execute a command, or shell script, or any other program. By
default, time command executes the given command or program. After
execution, it displays the statistics and resources usage on the standard
error.
7
time
1. Write Time Statistics Output to a File using -o option.
This option is to restrict sending the command results to standard error, but
writes results into output file. This option overwrites the specified file.
$ cat time.txt
0.00user 0.00system 0:02.00elapsed 0%CPU (0avgtext+0avgdata
2288maxresident)k0inputs+0outputs (0major+175minor)pagefaults 0swaps
$ cat time.txt
0.00user 0.00system 0:02.00elapsed 0%CPU (0avgtext+0avgdata
2288maxresident)k0inputs+0outputs (0major+175minor)pagefaults 0swaps
0.00user 0.00system 0:04.00elapsed 0%CPU (0avgtext+0avgdata
2288maxresident)k0inputs+0outputs (0major+176minor)pagefaults 0swaps
8
time
3. Display Percentage of CPU used – %P
You can provide output formatting choices using -f option. This option allows
user to provide output formatting options. It possibly does overriding the
format specified in the environment variable TIME. Following formatting
options are described below – %P, %M, %S, %e, %E, %C, %Z, %c, %x.
This option gives percentage of the CPU that the process of command (i.e. run
under time command) has got for its execution. This is just user + system
times divided by the total running time. It also prints a percentage sign.
$ /usr/bin/time -f "\t%P CPU Percentage" find / -name my-program.sh
/root/my-program.sh
82% CPU Percentage
Here, command output shows that find command took 82% of CPU.
Other Options
Display Maximum Resident Set Size – %M
Display Total Number of CPU-seconds – %S
Display Elapsed Real Time in Seconds – %e
Display Elapsed Real Time in Different Format – %E
Display Program Name and Command Line Arguments – %C
Display System Page Size in Bytes – %Z
Display Number of Context Switches – %c
9
Display Exit Status of a Command – %x
Man
The man pages are a user manual that is by default built into most Linux
distributions (i.e., versions) and most other Unix-like operating systems
during installation.
For example, the following provides information about the ls command (which
is used to list the contents of any specified directory):
man ls
The syntax to specify an article from a particular section is:
man section_number keyword
Thus, for example, the following would display the article about mount from
Section 2 instead of from the default Section 8:
man 2 mount
A simpler version of a man page, i.e., without backspaces and underscores, can
be obtained by piping (i.e., transferring) its output to the col command used
with its -b option. Thus, for example, the following would write such a version
of the man page about the pstree command (which shows the processes
currently on the system in a tree diagram) to a text file called pstree.txt (and
create a file with this name if it did not already exist):
man pstree | col -b > pstree.txt
10
pwd
Print the name of the working directory.
Syntax
cd [-L | -P [-e]] directory
13
mkdir
The mkdir command creates new directories in your file system.
mkdir [-m=mode] [-p] [-v] [-Z=context] directory [directory ...]
mkdir --version
mkdir –help
14
mkdir
Creates the directory /home/hope/Documents/pdf. If any of the parent
directories /home, /home/hope, or /home/hope/Documents do not already exist,
they will automatically be created.
mkdir -p /home/hope/Documents/pdf
15
cat
cat stands for "catenate." It reads data from files, and outputs their contents. It is
the simplest way to display the contents of a file at the command line.
Displaying Text Files
The simplest way to use cat is to give it the name of a text file. It will display the
contents of the text file on the screen. For instance:
cat mytext.txt
...will read the contents of mytext.txt and send them to standard output (your
terminal screen). If mytext.txt is very long, they will zoom past and you will only
see the last screen's worth of your document. If you want to view the document
page-by-page or scroll back and forth through the document, you can use a pager
or viewer such as pg, more, or less.
If you specify more than one file name, cat will display those files one after the
other, catenating their contents to standard output. So this command:
cat mytext.txt mytext2.txt
Will print the contents of those two text files as if they were a single file.
16
cat
Append A Text File's Contents To Another Text File
Instead of overwriting another file, you can also append a source text file
to another using the redirection operator ">>".
cat mytext.txt >> another-text-file.txt
...will read the contents of mytext.txt, and write them at the end of
another-text-file.txt. If another-text-file.txt does not already exist, it will be
created and the contents of mytext.txt will be written to the new file.
cat -s file.txt
Display the contents of file.txt, omitting any repeated blank lines.
17
cat
Copy A Text File
Normally you would copy a file with the cp command. You can use cat to
make copies of text files in much the same way.
cat sends its output to stdout (standard output), which is usually the
terminal screen. However, you can redirect this output to a file using the
shell redirection symbol ">".
cat mytext.txt > newfile.txt
...will read the contents of mytext.txt and send them to standard output;
instead of displaying the text, however, the shell will redirect the output to
the file newfile.txt. If newfile.txt does not exist, it will be created. If
newfile.txt already exists, it will be overwritten and its previous contents
will be lost, so be careful.
cat mytext.txt mytext2.txt > newfile.txt
18
ls
List Files using ls with no option
ls with no option list files and directories in bare format.
$ ls
0001.pcap Desktop Downloads index.html install.log.syslog Pictures Templates
anaconda-ks.cfg Documents fbcmd_update.php install.log Music Public Videos
List Files With option –l
Here, ls -l (-l is character not one) shows file or directory, size, modified date and
time, file or folder name and owner of file and its permission.
$ ls -l
total 176
-rw-r--r--. 1 root root 683 Aug 19 09:59 0001.pcap
-rw-------. 1 root root 1586 Jul 31 02:17 anaconda-ks.cfg
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Desktop
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Documents
drwxr-xr-x. 4 root root 4096 Aug 16 02:55 Downloads
-rw-r--r--. 1 root root 21262 Aug 12 12:42 fbcmd_update.php
View Hidden Files
$ ls -a
. .bashrc Documents .gconfd install.log .nautilus .pulse-cookie
.. .cache Downloads .gnome2 install.log.syslog .netstat.swp .recently-used.xbel
19
ls
List Files with Human Readable Format with option -lh
With combination of -lh option, shows sizes in human readable format.
$ ls -lh
total 176K
-rw-r--r--. 1 root root 683 Aug 19 09:59 0001.pcap
-rw-------. 1 root root 1.6K Jul 31 02:17 anaconda-ks.cfg
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Desktop
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Documents
List Files and Directories with ‘/’ Character at the end
Using -F option with ls command, will add the ‘/’ Character at the end each
directory.
$ ls -F
0001.pcap Desktop/ Downloads/ index.html install.log.syslog Pictures/ Templates/
anaconda-ks.cfg Documents/ fbcmd_update.php install.log Music/ Public/ Videos
List Files in Reverse Order
The following command with ls -r option display files and directories in reverse
order.
$ ls -r
Videos Public Music install.log fbcmd_update.php Documents anaconda-ks.cfg
Templates Pictures install.log.syslog index.html Downloads Desktop 0001.pcap 20
ls
Recursively list Sub-Directories
ls -R option will list very long listing directory trees. See an example of output of
the command.
$ ls -R
total 1384
-rw-------. 1 root root 33408 Aug 8 17:25 anaconda.log
-rw-------. 1 root root 30508 Aug 8 17:25 anaconda.program.log
./httpd:
total 132
-rw-r--r-- 1 root root 0 Aug 19 03:14 access_log
-rw-r--r--. 1 root root 61916 Aug 10 17:55 access_log-20120812
Sort Files by File Size
With combination of -lS displays file size in order, will display big in size first.
$ ls -lS
total 176
-rw-r--r--. 1 root root 48867 Jul 31 02:17 install.log
-rw-r--r--. 1 root root 46701 Jul 31 09:58 index.html
-rw-r--r--. 1 root root 21262 Aug 12 12:42 fbcmd_update.php
21
rmdir
The rmdir command removes empty directories from your filesystem.
rmdir [-p] [-v | --verbose] [--ignore-fail-on-non-empty] directory ...
rm --help
rm --version
Remove the directory mydir, if it is empty.
rmdir mydir
Remove the directories dir1, dir2, and dir3, if they are empty. If any are not
empty, an error message will be printed for that directory, and the others will be
removed.
rmdir dir1 dir2 dir3
Remove the directory dir/subdir if it is empty. Then, remove directory dir, if it is
empty after dir/subdir was removed.
rmdir dir/subdir dir
or
rmdir -p dir/subdir
22
cp
cp stands for copy. This command is used to copy files or group of files or
directory. It creates an exact image of a file on a disk with different file name. cp
command require at least two filenames in its arguments.
Syntax:
cp [OPTION] Source Destination
cp [OPTION] Source Directory
cp [OPTION] Source-1 Source-2 Source-3 Source-n Directory
First and second syntax is used to copy Source file to Destination file or Directory.
Third syntax is used to copy multiple Sources(files) to Directory.
Two file names
$ cp a.txt b.txt
Two file names : If the command contains two file names, then it copy the
contents of 1st file to the 2nd file. If the 2nd file doesn’t exist, then first it creates
one and content is copied to it. But if it existed then it is simply overwritten
without any warning. So be careful when you choose destination file name.
23
cp
cp Src_file1 Src_file2 Src_file3 Dest_directory
One or more arguments : If the command has one or more arguments, specifying
file names and following those arguments, an argument specifying directory
name then this command copies each source file to the destination directory with
the same name, created if not existed but if already existed then it will be
overwritten, so be careful !!.
$ ls
a.txt b.txt new
Initially new is empty
$ ls new
$ cp a.txt b.txt new
$ ls new
a.txt b.txt
24
cp
cp -R Src_directory Dest_directory
Two directory names : If the command contains two directory names, cp copies
all files of the source directory to the destination directory, creating any files or
directories needed. This mode of operation requires an additional option,
typically R, to indicate the recursive copying of directories.
25
cp
cp -i a.txt b.txt
cp: overwrite 'b.txt'? y
-i(interactive): i stands for Interactive copying. With this option system first
warns the user before overwriting the destination file. cp prompts for a response,
if you press y then it overwrites the file and with any other option leave it
uncopied.
$ cp -b a.txt b.txt
-b(backup): With this option cp command creates the backup of the destination
file in the same folder with the different name and in different format.
$ ls
a.txt b.txt
$ cp -b a.txt b.txt
$ ls
a.txt b.txt b.txt~
26
cp
$ cp -f a.txt b.txt
-f(force): If the system is unable to open destination file for writing operation
because the user doesn’t have writing permission for this file then by using -f
option with cp command, destination file is deleted first and then copying of
content is done from source to destination file.
$ ls -l b.txt
-r-xr-xr-x+ 1 User User 3 Nov 24 08:45 b.txt
User, group and others doesn't have writing permission.
$ cp a.txt b.txt
Without -f option, command not executed
cp: cannot create regular file 'b.txt': Permission denied
$ cp -f a.txt b.txt
With -f option, command executed successfully
27
cp
-r or -R: Copying directory structure. With this option cp command shows its
recursive behavior by copying the entire directory structure recursively.
Suppose we want to copy sicsr directory containing many files, directories into siu
directory(not exist).
$ ls sicsr/
a.txt b.txt b.txt~ Folder1 Folder2
28
cp
-r or -R: Copying directory structure. With this option cp command shows its
recursive behavior by copying the entire directory structure recursively.
Suppose we want to copy sicsr directory containing many files, directories into siu
directory(not exist).
$ ls sicsr/
a.txt b.txt b.txt~ Folder1 Folder2
29
cp
$ cp *.txt Folder1
Copying using * wildcard: The star wildcard represents anything i.e. all files and
directories. Suppose we have many text document in a directory and wants to
copy it another directory, it takes lots of time if we copy files 1 by 1 or command
becomes too long if specify all these file names as the argument, but by using *
wildcard it becomes simple.
$ cp *.txt Folder1
$ ls Folder1
a.txt b.txt c.txt d.txt e.txt
30
mv
mv stands for move. mv is used to move one or more files or directories from one
place to another in file system like UNIX. It has two distinct functions:
(i) It rename a file or folder.
(ii) It moves group of files to different directory.
No additional space is consumed on a disk during renaming. This command
normally works silently means no prompt for confirmation.
Syntax:
mv [Option] source destination
$ mv -i geek.txt b.txt
-i (Interactive): Like in cp, the -i option makes the command ask the user for
confirmation before moving a file that would overwrite an existing file, you have
to press y for confirm moving, any other key leaves the file as it is. This option
doesn’t work if the file doesn’t exist, it simply rename it or move it to new
location.
$ mv -i geek.txt b.txt
mv: overwrite 'b.txt'? Y
31
mv
mv stands for move. mv is used to move one or more files or directories from one
place to another in file system like UNIX. It has two distinct functions:
(i) It rename a file or folder.
(ii) It moves group of files to different directory.
No additional space is consumed on a disk during renaming. This command
normally works silently means no prompt for confirmation.
Syntax:
mv [Option] source destination
$ mv -i geek.txt b.txt
-f (Force): mv prompts for confirmation overwriting the destination file if a file is
write protected. The -f option overrides this minor protection and overwrite the
destination file forcefully and delete the source file.
$ mv -f geek.txt b.txt
$ mv -n geek.txt b.txt
-n (no-clobber): With -n option, mv prevent an existing file from being
overwritten. In the following example the effect is for nothing to happen as a file
would be overwritten.
$ mv -n geek.txt b.txt 32
chmod
chmod is used to change the permissions of files or directories.
Syntax
chmod options permissions file-name
permissions defines the permissions for the owner of the file (the "user"),
members of the group who owns the file (the "group"), and anyone else
("others"). There are two ways to represent these permissions: with symbols
(alphanumeric characters), or with octal numbers (the digits 0 through 7).
34
chmod
drwxr-xr-x 2 user group 4.0K 2009-08-13 10:16 docs
-rw-r--r-- 1 user group 8.1K 2009-07-09 16:23 roster.py
lrwxrwxrwx 2 user group 4.0K 2009-08-13 10:16 team.docs
The first character represents the type of file. The remaining nine bits in
groups of three represent the permissions for the user, group, and global
respectively. Each stands for:
r: Read
w: Write
x: eXecute
35
chmod
File permissions settings, numerical values, and their meanings
-rw------- (600) Only the owner has read and write permissions.
-rw-r--r-- (644) Only the owner has read and write permissions; the group and
others have read only.
-rwx------ (700) Only the owner has read, write, and execute permissions.
-rwxr-xr-x (755) The owner has read, write, and execute permissions; the group
and others have only read and execute.
-rwx--x--x (711) The owner has read, write, and execute permissions; the group
and others have only execute.
-rw-rw-rw- (666) Everyone can read and write to the file. (Be careful with these
permissions.)
-rwxrwxrwx (777) Everyone can read, write, and execute. (Again, this permissions
setting can be hazardous.)
Directory permissions settings, numerical values, and their meanings
Setting Numerical Meaning
drwx------ (700) Only the user can read, write in this directory.
drwxr-xr-x (755) Everyone can read the directory; users and groups
have read and execute permissions. 36
sort
sort sorts the contents of a text file, line by line.
sort is a simple and very useful command which will rearrange the lines in a
text file so that they are sorted, numerically and alphabetically. By default, the
rules for sorting are:
•Lines starting with a number will appear before lines starting with a letter.
•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.
•Lines starting with a lowercase letter will appear before lines starting with the
same letter in uppercase.
The rules for sorting can be changed according to the options you provide to
the sort command.
Syntax :
$ sort filename.txt
37
sort
Suppose you create a $ sort file.txt -n Option : To sort
data file with name abhishek the file with numeric
file.txt. chitransh data present inside.
divyam $ cat > file1.txt
$ cat > file.txt harsh 50
abhishek naveen 39
chitransh rajan 15
satish satish 89
rajan -r Option: Sorting In 200
naveen Reverse Order $ sort -n file1.txt
divyam $ sort –r file.txt 15
harsh satish 39
rajan 50
naveen 89
harsh 200
divyam
chitransh
abhishek
38
sort
-nr option : To sort a file with -o Option : Unix also provides us with special
numeric data in reverse order facilities like if you want to write the output
$ sort -nr file1.txt to a new file, output.txt
200 $ sort inputfile.txt > filename.txt
89
(or)
50
39 $ sort -o filename.txt inputfile.txt
15
-c option : To check if the file -k Option : Use the -k (sorting key) option to
given is already sorted or not. sort on a certain column. For example, use “-k
Audi 2” to sort on the second column.
Cadillac $ sort -k 2n employee.txt
BMW guard 3000
Dodge
clerk 4000
$ sort -c cars.txt
sort: cars.txt:3: disorder: peon 4500
BMW manager 5000
Note : If there is no output employee 6000
then the file is considered to director 9000
be already sorted
39
sort
$ sort -u cars.txt
$ cat cars.txt
Audi
BMW
Cadillac
Dodge
40
mount
The Linux mount command is used to mount USBs, DVDs, SD cards, and other
types of storage devices on a computer running the Linux operating system.
Linux uses a directory tree structure. Unless the storage device is mounted to
the tree structure, the user can't open any of the files on the computer.
This tells the kernel to attach the file system found on device (which is of type
type) at the directory dir. The previous contents (if any) and owner and mode of
dir become invisible, and as long as this file system remains mounted, the
pathname dir refers to the root of the file system on device.
$ lpr myfile.txt
Submits a request to print the file myfile.txt.
43
history
All of our services are currently running on Linux. In Linux, there is a very
useful command to show you all of the last commands that have been recently
used. The command is simply called history, but can also be accessed by
looking at your .bash_history in your home folder.
Print History
$ history
1 ip a
2 exit
3 ls –la
4 pwd
Print ‘n’ Lines
$ history 3
16 passwd
17 getenforce
18 history 3
The who command displays the following information for each user currently
logged in to the system if no option is provided :
1.Login name of the users
2.Terminal line numbers
3.Login time of the users in to system
4.Remote host name of the user
$ who
hduser tty7 2018-03-18 19:08 (:0)
To show time of the system when it booted last time
$ who -b -H
NAME LINE TIME PID COMMENT
system boot 2018-03-18 19:07 45
passwd
The passwd command is used to change the password of a user account. A
normal user can run passwd to change their own password, and a system
administrator (the superuser) can use passwd to change another user's
password, or define how that account's password can be used or changed.
passwd syntax
passwd [OPTION] [USER]
47
kill
Option Description
-signal, The name, abbreviated name, or number of the signal to be sent,
-s signal preceded by a dash. For example, -SIGTERM, -TERM, or -15. To
view a list of available signals, use the -l or -L options (see
below), or refer to our list of Linux signals.
pid A numeric process ID. If you're not sure what the PID is of a
process, use the pscommand to list it, e.g., ps -aux.
-l, -- List available signal names. With -l or --list, lists all signal names.
list[=signal] With --list=signal, translates a number into its signal name.
-L, --table List available signal names and numbers in a table.
48
Kill - Examples
kill -9 -1
Kill all processes the user has permission to kill, except the root process (PID 1)
and the kill process itself.
kill -l
List all available signal names. Sample output:
HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM TERM STKFLT
CHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH POLL PWR SYS
/bin/kill -L
List available signals and their numbers in a table format. Sample output:
49
tar
The tar program is used to create, maintain, modify, and extract files that are
archived in the tar format. "tar" stands for tape archive. It is an archiving file
format.
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 create 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
50
tar - Examples
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
Extracting files from Archive using option -xvf : This command extracts files
from Archives.
$ tar xvf file.tar
Output :
os2.c
os3.c
os4.c
51
tar - Examples
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
Extracting a gzip tar Archive *.tar.gz using option -xvzf : This command extracts
files from tar archived file.tar.gz files.
52
zip
The zip program is used to package and compress files. zip is useful for
packaging a set of files for distribution, for archiving files, and for saving disk
space by temporarily compressing unused files or directories.
Syntax
zip options archive inpath inpath ...
For example, if foo.zip exists and contains foo/file1 and foo/file2, and the
directory foo contains the files foo/file1 and foo/file3, then:
zip -r foo.zip foo
will replace foo/file1 in foo.zip and add foo/file3 to foo.zip. After this, foo.zip
contains foo/file1, foo/file2, and foo/file3, with foo/file2 unchanged from
before.
53
wc
The wc (word count) command in Unix/Linux operating systems is used to find
out number of newline count, word count, byte and characters count in a files
specified by the file arguments.
Syntax
$ wc [options] filenames
The following are the options and usage provided by the command.
wc -l Prints the number of lines in a file.
wc -w prints the number of words in a file.
wc -c Displays the count of bytes in a file.
wc -m prints the count of characters from a file.
wc -L prints only the length of the longest line in a file.
54
wc - Examples
Create a data file with $ wc tecmint.txt $ wc -m tecmint.txt
name file.txt. 12 16 112 Output
tecmint.txt 112 tecmint.txt
$ cat file.txt The three numbers (number of characters)
Red Hat 12,16,112 represents
CentOS number of lines (12), $ wc -L tecmint.txt
Fedora number of words (16) 16 tecmint.txt
Debian and number of ‘-L‘, it can be used to
Scientific Linux bytes(112) of the file. print out the length of
OpenSuse longest (number of
Ubuntu The same can be characters) line in a
Xubuntu done separately as file.
Linux Mint follows:
Pearl Linux wc -l tecmint.txt
Slackware wc -w tecmint.txt
Mandriva wc -c tecmint.txt
55
grep
Option Description
The grep filter searches a
-c This prints only a count of the lines that match a
file for a particular pattern
pattern
of characters, and displays
-h Display the matched lines, but do not display the
all lines that contain that
filenames
pattern. The pattern that
-i Ignores, case for matching
is searched in the file is
-l Displays list of a filenames only
referred to as the regular
expression (grep stands -n Display the matched lines and their line numbers
for globally search for -v This prints out all the lines that do not matches
regular expression and the pattern
print out). -e exp Specifies expression with this option. Can use
multiple times
Syntax: -f file Takes patterns from file, one per line.
grep [options] pattern [files]
-E Treats pattern as an extended regular expression
(ERE)
The following are the
options and usage -w Match whole word
provided by the -o Print only the matched parts of a matching line,
command. with each such part on a separate output line
56
grep - Examples
Consider the below file Case insensitive search: Displaying the count of
as an input. The -i option enables to number of matches :
search for a string case We can find the
$ cat > file.txt insensitively in the give number of lines that
unix is great os. unix is file. It matches the matches the given
opensource. unix is free words like “UNIX”, string/pattern.
os. “Unix”, “unix”. $grep -c "unix" geekfile.txt
learn operating system. $grep -i "UNix" geekfile.txt Output:
Unix linux which one Output 2
you choose. unix is great os. unix is
uNix is easy to learn. opensource. unix is free
unix is a multiuser os. os.
Learn unix. unix is a Unix linux which one
powerful. you choose.
uNix is easy to learn.
unix is a multiuser
os.Learn unix. unix is a
powerful.
57
grep - Examples
Display the file names Checking for the whole Displaying only the
that matches the words in a file: By matched pattern: By
pattern: We can just default, grep matches default, grep displays
display the files that the given string/pattern the entire line which
contains the given even if it found as a has the matched
string/pattern. substring in a file. string. We can make
The -w option to grep the grep to display only
$grep -l "unix" * makes it match only the the matched string by
or whole words. using the -o option.
$grep -l "unix" f1.txt
f2.txt f3.xt f4.txt $ grep -w "unix" geekfile.txt $ grep -o "unix" geekfile.txt
Output Output
Output: unix is great os. unix is unix
geekfile.txt opensource. unix is free unix
os. unix
uNix is easy to unix
learn.unix is a multiuser unix
os.Learn unix .unix is a unix
powerful. 58