Monday, January 5, 2015

Linux for new penguins

1. General overview of the Linux files system – Files, Sorts
of files, system configuration file and run levels.
A filesystem is the methods and data structures that an
operating system uses to keep track of files on a disk or
partition; that is, the way the files are organized on the disk.
"On a UNIX system, everything is a file; if something is not a
file, it is a process."
This statement is true because there are special files that are
more than just files (named pipes and sockets, for instance),
but to keep things simple, saying that everything is a file is
an acceptable generalization. A Linux system, just like UNIX,
makes no difference between a file and a directory, since a
directory is just a file containing names of other files.
Programs, services, texts, images, and so forth, are all files.
Input and output devices, and generally all devices, are
considered to be files, according to the system.
There are seven basic types of file types in Linux.
Regular Files: they contain normal data, for example text files,
executable files or programs, input for or output from a program
and so on
Directories: Directories are files that are lists of other files
Character Device Files: Character special files or character
devices relate to devices through which the system transmits
data one character at a time. These device nodes often serve for
stream communication with devices such as mice, keyboards,
virtual terminals, and serial modems, and usually do not support
random access to data. In most implementations, character
devices use unbuffered input and output routines. The system
reads each character from the device immediately or writes each
character to the device immediately.
Block Device Files: Block special files or block devices
correspond with devices that move data in the form of blocks.
These device nodes interface the devices, such as hard disks,
CD-ROM drives, flash drives and other addressable regions ofmemory. Block devices support random access and seeking, and
generally use buffered input and output routines. The operating
system allocates a data buffer to hold a single block each for
input and output. When a program sends a request to read data
from or to write data to the device, the system stores each
character of that data in the appropriate buffer. When the
buffer fills up, the appropriate operation takes place (data
transfer) and the system clears the buffer.
Local Domain Sockets: A Local (UNIX or Linux) domain socket or IPC
socket (inter-process communication socket) is a data communications
endpoint for exchanging data between processes executing within the
same host operating system.
Named Pipes:
A named pipe is really just a special kind of file (a
FIFO file) on the local hard drive. Unlike a regular file, a FIFO file
does not contain any user information. Instead, it allows two or more
processes to communicate with each other by reading/writing to/from
this file.
Symbolic Links: (also symlink or soft link) is a special type of file
that contains a reference to another file or directory in the form of
an absolute or relative path and that affects pathname resolution.
$ ls -lh
-rw-r----- 1 ramesh team-dev 5.0K Jun 13 15:27 mthesaur.txt.gz
• 1st Character – File Type: First character specifies the type of
the file.
In the example above the hyphen (-) in the 1st character
indicates that this is a normal file. Following are the possible
file type options in the 1st character of the ls -l output.
File type
Explanation
- Regular file
d Directory
c Character Device
b Block Devices Local Domain Socket
p Named Pipe
l Symbolic Link
•
Field 1 – File Permissions: Next 9 character specifies the files
permission. Each 3 characters refers to the read, write, execute
permissions for user, group and others. In this example, -rw-r—–
indicates read-write permission for user, read permission for
group, and no permission for others.
Yellow color permission is for owner.Red color permission is for
group.Grey color is permission for others
•
Field 2 – Number of links: Second field specifies the number of
links for that file. In this example, 1 indicates only one link
to this file.
• Field 3 – Owner: Third field specifies owner of the file. In this
example, this file is owned by username ‘ramesh’.
• Field 4 – Group: Fourth field specifies the group of the file. In
this example, this file belongs to ”team-dev’ group.
• Field 5 – Size: Fifth field specifies the size of file. In this
example, ’9275204′ indicates the file size.
• Field 6 – Last modified date & time: Sixth field specifies the
date and time of the last modification of the file. In this
example, ‘Jun 13 15:27′ specifies the last modification time of
the file.
• Field 7 – File name: The last field is the name of the file. In
this example, the file name is mthesaur.txt.gz.
Note:-
Difference between Soft link and hard link
Hard links cannot link directories & cannot cross file system
boundaries. Symbolic links allows to create links between directories
and Can cross file system boundaries.
Unix files consist of two parts: the data part and the filename part.
The data part is associated with something called an 'inode'. The
inode carries the map of where the data is, the file permissions, etc.
for the data.
.---------------> ! data ! ! data ! etc
+------+ !------+
! permbits, etc ! data addresses !
+------------inode---------------+
/
The filename part carries a name and an associated inode number..--------------> ! permbits, etc ! addresses !
/
+---------inode-------------+
! filename ! inode # !
+--------------------+
More than one filename can reference the same inode number; these files
are said to be 'hard linked' together.
! filename ! inode # !
+--------------------+
\
>--------------> ! permbits, etc ! addresses !
/
+---------inode-------------+
! othername ! inode # !
+---------------------+
On the other hand, there's a special file type whose data part carries a
path to another file. Since it is a special file, the OS recognizes the
data as a path, and redirects opens, reads, and writes so that, instead of
accessing the data within the special file, they access the data in the
file named by the data in the special file. This special file is called a
'soft link' or a 'symbolic link' (aka a 'symlink').
! filename ! inode # !
+--------------------+
\
.-------> ! permbits, etc ! addresses !
+---------inode-------------+
/
/
/
.----------------------------------------------'
(
'--> !"/path/to/some/other/file"!
+---------data-------------+
/
}
.~ ~ ~ ~ ~ ~ ~
}-- (redirected at open() time)
(
}
'~~> ! filename ! inode # !
+--------------------+
\
'------------> ! permbits, etc ! addresses !
+---------inode-------------+
/
/
.----------------------------------------------------'
(
'-> ! data ! ! data ! etc.
+------+ +------+Table 3-2. Subdirectories of the root directory
Directory
Content
Common programs, shared by the system, the system
/bin
administrator and the users.Directory
/boot
/dev
/etc
/home
/initrd
/lib
/lost+found
/misc
/mnt
/net
/opt
/proc
/root
/sbin
/tmp
/usr
/var
Content
The startup files and the kernel, vmlinuz. In some recent
distributions also grub data. Grub is the Grand Unified
Boot loader and is an attempt to get rid of the many
different boot-loaders we know today.
Contains references to all the CPU peripheral hardware,
which are represented as files with special properties.
Most important system configuration files are in /etc,
this directory contains data similar to those in the
Control Panel in Windows
Home directories of the common users.
(on some distributions) Information for booting. Do not
remove!
Library files, includes files for all kinds of programs
needed by the system and the users.
Every partition has a lost+found in its upper directory.
Files that were saved during failures are here.
For miscellaneous purposes.
Standard mount point for external file systems, e.g. a
CD-ROM or a digital camera.
Standard mount point for entire remote file systems
Typically contains extra and third party software.
A virtual file system containing information about system
resources. More information about the meaning of the
files in proc is obtained by entering the command man
proc in a terminal window. The file proc.txt discusses
the virtual file system in detail.
The administrative user's home directory. Mind the
difference between /, the root directory and /root, the
home directory of the root user.
Programs for use by the system and the system
administrator.
Temporary space for use by the system, cleaned upon
reboot, so don't use this for saving any work!
Programs, libraries, documentation etc. for all user-
related programs.
Storage for all variable files and temporary files
created by users, such as log files, the mail queue, the
print spooler area, space for temporary storage of files
downloaded from the Internet, or to keep an image of a CD
before burning it.
Press the power button on your system, and after few moments
you see the Linux login prompt.Have you ever wondered what happens behind the scenes from the
time you press the power button until the Linux login prompt
appears?
The following are the 6 high level stages of a typical Linux
boot process.
1. BIOS
•
•
•
•
BIOS stands for Basic Input/Output System
Performs some system integrity checks
Searches, loads, and executes the boot loader program.
It looks for boot loader in floppy, cd-rom, or hard drive.
You can press a key (typically F12 of F2, but it depends on
your system) during the BIOS startup to change the boot
sequence.
• Once the boot loader program is detected and loaded into the
memory, BIOS gives the control to it.
• So, in simple terms BIOS loads and executes the MBR boot
loader.
2. MBR
• MBR stands for Master Boot Record.
• It is located in the 1st sector of the bootable disk.
Typically /dev/hda, or /dev/sda
• MBR is less than 512 bytes in size. This has three
components 1) primary boot loader info in 1st 446 bytes 2)
partition table info in next 64 bytes 3) mbr validation
check in last 2 bytes.
• It contains information about GRUB (or LILO in old systems).
• So, in simple terms MBR loads and executes the GRUB boot
loader.
3. GRUB
• GRUB stands for Grand Unified Bootloader.
• If you have multiple kernel images installed on your system,
you can choose which one to be executed.
• GRUB displays a splash screen, waits for few seconds, if you
don’t enter anything, it loads the default kernel image as
specified in the grub configuration file.
• GRUB has the knowledge of the filesystem (the older Linux
loader LILO didn’t understand filesystem).• Grub configuration file is /boot/grub/grub.conf
(/etc/grub.conf is a link to this). The following is sample
grub.conf of CentOS.
#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/boot/grub/splash.xpm.gz
hiddenmenu
title CentOS (2.6.18-194.el5PAE)
root (hd0,0)
kernel /boot/vmlinuz-2.6.18-194.el5PAE ro
root=LABEL=/
initrd /boot/initrd-2.6.18-194.el5PAE.img
• As you
initrd
• So, in
initrd
notice from the above info, it contains kernel and
image.
simple terms GRUB just loads and executes Kernel and
images.
4. Kernel
• Mounts the root file system as specified in the “root=” in
grub.conf
• Kernel executes the /sbin/init program
• Since init was the 1st program to be executed by Linux
Kernel, it has the process id (PID) of 1. Do a ‘ps -ef |
grep init’ and check the pid.
• initrd stands for Initial RAM Disk.
• initrd is used by kernel as temporary root file system until
kernel is booted and the real root file system is mounted.
It also contains necessary drivers compiled inside, which
helps it to access the hard drive partitions, and other
hardware.
5. Init
• Looks at the /etc/inittab file to decide the Linux run
level.
• Following are the available run levels
• 0 – halt
• 1 – Single user mode
• 2 – Multiuser, without NFS
• 3 – Full multiuser mode•
•
•
•
• 4 – unused
• 5 – X11
• 6 – reboot
Init identifies the default initlevel from /etc/inittab and
uses that to load all appropriate program.
Execute ‘grep initdefault /etc/inittab’ on your system to
identify the default run level
If you want to get into trouble, you can set the default run
level to 0 or 6. Since you know what 0 and 6 means, probably
you might not do that.
Typically you would set the default run level to either 3 or
5.
6. Runlevel programs
• When the Linux system is booting up, you might see various
services getting started. For example, it might say
“starting sendmail .... OK”. Those are the runlevel programs,
executed from the run level directory as defined by your run
level.
• Depending on your default init level setting, the system
will execute the programs from one of the following
directories.
• Run level 0 – /etc/rc.d/rc0.d/
• Run level 1 – /etc/rc.d/rc1.d/
• Run level 2 – /etc/rc.d/rc2.d/
• Run level 3 – /etc/rc.d/rc3.d/
• Run level 4 – /etc/rc.d/rc4.d/
• Run level 5 – /etc/rc.d/rc5.d/
• Run level 6 – /etc/rc.d/rc6.d/
• Please note that there are also symbolic links available for
these directory under /etc directly. So, /etc/rc0.d is
linked to /etc/rc.d/rc0.d.
• Under the /etc/rc.d/rc*.d/ directories, you would see
programs that start with S and K.
• Programs starts with S are used during startup. S for
startup.
• Programs starts with K are used during shutdown. K for kill.
• There are numbers right next to S and K in the program
names. Those are the sequence number in which the programs
should be started or killed.
• For example, S12syslog is to start the syslog deamon, which
has the sequence number of 12. S80sendmail is to start the
sendmail daemon, which has the sequence number of 80. So,syslog program will be started before sendmail.
There you have it. That is what happens during the Linux boot
process.
What are system configuration files?
System configuration files are those files to be referred by the
kernel for correct working of the system and customizing the
environment up to a extent.
File Description
.bash_history
For users of the bash shell, a file containing up to 500 of the most
recent commands available for recall using the up and down arrow keys.
.bash_logout
Script that is run by the bash shell when the user logs out of the
system
.bash_profile
Initialization script that is run by the bash shell upon login in
order to setup variables and aliases. When bash is started as the
default login shell, it looks for the .bash_profile file in the user’s
home directory; if not found, it looks for .bash_login. If there is no
.bash_login file, it then looks for a .profile file.
.bashrc
Initialization script executed whenever the bash shell is started in
some way other than a login shell. It is better to put system-wide
functions and aliases in /etc/bashrc, which will be presented later in
the book.
.login
The initialization script that is run whenever a user login occurs.
.logout
The script that is automatically run whenever a user logout occurs.
.profile
Put default system-wide environment variables in /etc/profile.
File
/boot/vmlinuz
/dev/fd0
/dev/fd0H1440
/dev/hda
Description
The Linux kernel file. File naming conventions may
include release information
Device file for the first floppy disk drive on the
system
Device driver for the first floppy drive in high
density mode, commonly invoked when formatting a
floppy diskette for that density
Device file for the first IDE hard drive on the system/dev/hdc
/dev/null
/etc/aliases
/etc/bashrc
/etc/crontab
/etc/exports
/etc/fstab
/etc/group
/etc/grub.conf
/etc/hosts
/etc/hosts.allow
/etc/hosts.deny
/etc/inittab
/etc/issue
/etc/lilo.conf
/etc/modules.conf
/etc/motd
/etc/mtab
/etc/passwd
/etc/printcap
/etc/profile
Commonly, the IDE CDROM drive device file which often
is a symbolic link called to /dev/cdrom, the real
CDROM driver file.
A dummy device which contains nothing. It is sometimes
useful to send output to this device to make it go
away forever.
Contains aliases used by sendmail and other mail
transport agents. Whenever this file is changed, the
newaliases utility must be run to notify sendmail of
the changes
Contains global defaults and aliases used by the bash
shell
A parent shell script to run commands periodically. It
invokes hourly, daily, weekly, and monthly scripts.
Contains a list of filesystems which may be made
available to other systems on the network via NFS.
The file system table contains the description of what
disk devices are available at what mount points.
Holds information regarding security group
definitions.
The grub boot loader configuration file.
Contains host names and their corresponding IP
addresses used for name resolution whenever a DNS
server is unavailable
Contains a list of hosts allowed to access services on
this computer.
Contains a list of hosts forbidden to access services
on this computer.
Describes how the INIT process should set up the
system in various run levels
Contains the pre-login message, often over written by
the /etc/rc.d/rc.local script in Red Hat and some
other rpm-based Linux distributions
The lilo boot loader configuration file
Holds options for configurable system modules
This is the ”message of the day” file which is printed
upon login. It can be overwritten by
/etc/rc.d/rc.local Red Hat on startup.
Status information for currently mounted devices and
partitions
Contains information regarding registered system
users. Passwords are typically kept in a shadow file
for better security.
Holds printer setup information
Contains global defaults for the bash shell/etc/resolv.conf
/etc/securetty
/etc/termcap
/proc/cpuinfo
/proc/filesystems
/proc/interrupts
/proc/ioports
/proc/meminfo
/proc/modules
/proc/mounts
/proc/stat
/proc/swaps
/proc/version
/var/log/lastlog
/var/log/messages
/var/log/wtmp
A list of domain name servers (DNS) used by the local
machine
This file contains a list of terminals where root can
login
An extensive ASCII text file defining the properties
of consoles, terminals, and printers
Contains CPU related information
Holds information regarding filesystems that are
currently in use
Stores the interrupts that are currently being used
A list of the I/O addresses used by devices connected
to the server
Contains memory usage information for both physical
memory and swap
Lists currently loaded kernel modules
Displays currently mounted file systems
Contains various statistics about the system, such as
the number of page faults since the system was last
booted
Holds swap file utilization information
Contains Linux version information
Stores information about the last boot process
Contains messages produced by the syslog daemon during
the boot process
A binary data file holding login time and duration for
each user currently on the system
Important Directories
Although organizations have made strides toward consistency via
standards such as the Linux File system Hierarchy Standard (FHS),
different Linux distributions still have somewhat different directory
structures. The following rendering exemplifies a typical Red Hat
effort toward standardization of where files are stored according to
type and use.
Directory
Description
/bin
All binaries needed for the boot process and to
run the system in single-user mode, including
essential commands such as cd, ls, etc.
/boot
Holds files used during the boot process along
with the Linux kernel itself
/dev
Contains device files for all hardware devices on
the system/etc
/etc/init.d
/etc/profile.d
/etc/rc.d
/etc/rc.d/init.d
/etc/rc.d/rc?.d
/etc/skel
/etc/X11
/home
/lib
/mnt
/proc
/root
/sbin
/tmp
/usr
/usr/bin
/usr/bin/X11
/usr/include
/usr/share
/usr/lib
/usr/local/bin
/usr/sbin
Files used by application subsystems such as
mail, the Oracle database, etc.
Contains various service startup scripts
Holds application setup scripts run by
/etc/profile upon login
Contains subdirectories which contain run level
specific scripts
run level initialization scripts
Where ‘?’ is a number corresponding to the
default run level. Contains symbolic links to
scripts which are in /etc/rc.d/init.d. for
services to be started and stopped at the
indicated run level.
Holds example dot files used to populate a new
user's home directory.
Contains subdirectories and configuration files
for the X Window system
User home directories
Some shared library directories, files, and links
The typical mount point for the user-mountable
devices such as floppy drives and CDROM
Virtual file system that provides system
statistics. It doesn't contain real files but
provides an interface to runtime system
information.
Home directory for the root user
Commands used by the super user for system
administrative functions
A standard repository for temporary files created
by applications and users.
Directory contains subdirectories with source
code, programs, libraries, documentation, etc.
Contains commands available to normal users
X Window system binaries
Holds include files used in C programs
Contains shared directories for man files, info
files, etc.
Library files searched by the linker when
programs are compiled
Common executable application files local to this
system
Commands used by the super user for system
administrative functions/var
Administrative files such as log files, locks,
spool files, and temporary files used by various
utilities
A runlevel is a preset operating state on a Unix-like operating
system . A system can be booted into (i.e., started up into) any of
several runlevels, each of which is represented by a single digit
integer. Each runlevel designates a different system configuration and
allows access to a different combination of processes (i.e., instances
of executing programs ).
typing the init 3 command will move system to run level 3:
# init 3
On most Linux server system default run level is 3 and on most Linux
Desktop system default run level is 5. The default run level is
defined by the initdefault line at the top of /etc/inittab file under
CentOS / Fedora / Redhat / RHEL / Debian Linux. To change the default
run level, edit /etc/inittab file, and edit entry initdefault:
# vi /etc/inittab
Set initdefault to 5, so that you can boot to X next time when Linux
comes up:
id:5:initdefault:
Save and close the file. Reboot the system to see changes:
# reboot
RunlevelRun
Level
0
Generic Fedora Core Slackware Debian
Halt
Single-user
mode Halt
Single-user
mode Halt
Single-user
mode
2 Basic multi-
user mode
(without
networking) User
definable
(Unused) 3 Full (text
based) multi-
user mode Multi-user
mode 4 Not used Not used Halt
Single-user
mode
User
definable -
configured
the same as
runlevel 3
Multi-user
mode -
default
Slackware
runlevel
X11 with
KDM/GDM/XDM
(session
managers)
1
5 Full (GUI
based) multi-
user mode
6 Reboot
Full multi-
user mode
(with an X-
based login
screen) -
default
runlevel
Reboot
Multi-user
mode
Multi-user
mode
User
definable -
configured
the same as
runlevel 3 Multi-user
mode
Reboot Reboot
2. File compression/decompression utilities - zip, gzip, tar etc.
Archiving means that you take 10 files and combine them into one file,
with no difference in size.
Compressing means reducing the size of file. we generally compress and
archive at the same time.
Get the Best Compression Possible with zip
-[0-9]
It's possible to adjust the level of compression that zip uses when it
does its job. The zip command uses a scale from 0 to 9, in which 0
means "no compression at all" (which is like tar, as you'll see
later), 1 means "do the job quickly, but don't bother compressing very
much," and 9 means "compress the heck out of the files, and I don't
mind waiting a bit longer to get the job done." The default is 6, but
modern computers are fast enough that it's probably just fine to use 9
all the time.#zip
-[0-9]
archivename.zip
zip -9 s9.zip *
files_to_be_zipped
(Zipping all files in directory )
ls -l
mkdir syyed
mv s9.zip syyed
cd syyed/
ls
unzip s9.zip
unzip
Expanding a Zip archive isn't hard at all. To create a zipped archive,
use the zip command; to expand that archive, use the unzip command.
unzip s9.zip
gzip
Using gzip is a bit easier than zip in some ways. With zip, you need
to specify the name of the newly created Zip file or zip won't work;
with gzip, though, you can just type the command and the name of the
files you want to compress. You should be aware of a very big
difference between zip and gzip: When you zip a file, zip leaves the
original behind so you have both the original and the newly zipped
file, but when you gzip a file, you're left with only the new gzipped
file. The original is gone.
#gzip -[0-9] files_to_be_zipped (For gzipping the files)
#gzip -[0-9]r files_to_be_zipped (for gzipping recursively)
gunzip is used for decompressing the gzipped files
gunzip
gunzip
files_for_decompres (For reversing gzip)
–r
gzip -r9
gunzip –r
files_for_decompres (for decompressing recursively)
*
(compressing all files recursively)
*
gzip syed.txt
(decompressing all files recursively)
;
gunzip syed.txt.gz;
(this will give us syed.txt.gz)
(this will give us syed.txt)bzip2
Working with bzip2 is pretty easy if you're comfortable with gzip, as
the creators of bzip2 deliberately made the options and behavior of
the new command as similar to its progenitor as possible.
bzip2 -[0-9]
file_to_be_compressed
bzip2 -[0-9]r
recursively)
file_to_be_compressed
(compressing files
bunzip2
In the same way that bzip2 was purposely designed to emulate gzip as
closely as possible, the way bunzip2 works is very close to that of
gunzip.
bzip2 file_to_be_compressed
bunzip2 file_to_be_decompressed.bz2
Archive Files with tar
-cf
Remember, tar doesn't compress; it merely archives (the resulting
archives are known as tar balls )
Instead, tar uses other programs, such as gzip or bzip2, to compress
the archives that tar creates. Even if you're not going to compress
the tarball, you still create it the same way with the same basic
options: -c (or --create), which tells tar that you're making a
tarball, and -f (or --file), which is the specified filename for the
tarball.
$ ls -l
scott scott 102519 job.txt
scott scott 1236574 moby-dick.txt
scott scott 508925 paradise_lost.txt
$ tar -cf moby.tar *.txt
$ ls -l
scott scott 102519 job.txt
scott scott 1236574 moby-dick.txt
scott scott 1853440 moby.tar
scott scott 508925 paradise_lost.txtWhat's really cool about tar is that it's designed to compress entire
directory structures, so you can archive a large number of files and
subdirectories in one fell swoop.
$ ls -lF
drwxr-xr-x scott scott 168 moby-dick/
$ ls -l moby-dick/*
scott scott 102519 moby-dick/job.txt
scott scott 1236574 moby-dick/moby-dick.txt
scott scott 508925 moby-dick/paradise_lost.txt
moby-dick/bible:
scott scott 207254 genesis.txt
scott scott 102519 job.txt
$ tar -cf moby.tar moby-dick/
$ ls -lF
scott scott
168 moby-dick/
scott scott 2170880 moby.tar
There's a way that should be followed to archive and compress at the
same time using tar. It involves two new options for tar: -z (or
--gzip), which invokes gzip from within tar so you don't have to do so
manually, and -v (or --verbose), which isn't required here but is
always useful, as it keeps you notified as to what tar is doing as it
runs.
$ ls -l moby-dick/*
scott scott 102519 moby-dick/job.txt
scott scott 1236574 moby-dick/moby-dick.txt
scott scott 508925 moby-dick/paradise_lost.txt
moby-dick/bible:
scott scott 207254 genesis.txt
scott scott 102519 job.txt
$ tar -zcvf moby.tar.gz moby-dick/
moby-dick/
moby-dick/job.txt
moby-dick/bible/
moby-dick/bible/genesis.txt
moby-dick/bible/job.txt
moby-dick/moby-dick.txt
moby-dick/paradise_lost.txt
$ ls -l
scott scott 168 moby-dick
scott scott 846049 moby.tar.gz
The usual extension for a file that has had the tar and then the gzip
commands used on it is .tar.gz; however, you could use .tgz and
.tar.gzip if you like.Note - It's entirely possible to use bzip2 with tar instead of gzip.
Your command would look like this (note the -j option, which is where
bzip2 comes in):
$ tar -jcvf moby.tar.bz2 moby-dick/
In that case, the extension should be .tar.bz2, although you may also
use .tar.bzip2, .tbz2, or .tbz. Yes, it's very confusing that using
gzip or bzip2 might both result in a file ending with .tbz. This is a
strong argument for using anything but that particular extension to
keep confusion to a minimum.
In same way, how to extract a tarball. We will use –x switch to
extract in following manner.
tar -xvf moby.tar
tar -zxvf moby.tar.gz
tar -jxvf moby.tar.bz2
3. Basics of managing files and directories - Viewing file
properties, Creating/deleting files and directories,
Moving/Copying/Removing files, Finding files –
which/find/locate/grep
root@Troy:~# stat hardware.txt
File: `hardware.txt'
Size: 14877
Device: 803h/2051d
Blocks: 32 IO Block: 4096
Inode: 15470100 Links: 1
Access: (0644/-rw-r--r--)
Uid: (
0/
root)
Access: 2012-07-22 20:52:00.512841858 +0530
Modify: 2012-07-22 20:51:34.248842284 +0530
Change: 2012-07-22 20:51:34.248842284 +0530
Birth: -
Details of Linux Stat Command Output
• File: – Absolute path name of the file.
• Size: – File size in bytes.
Gid: (
regular file
0/
root)• Blocks: – Total number of blocks used by this file.
• IO Block: – IO block size for this file.
• regular file – Indicates the file type. This indicates that
this is a regular file. Following are available file types.
• regular file. ( ex: all normal files ).
• directory. ( ex: directories ).
• socket. ( ex: sockets ).
• symbolic link. ( ex: symbolic links. )
• block special file ( ex: hard disk ).
• character special file. ( ex: terminal device file ).
• Device: 803h/2051d Device number in hex and device number in
decimal
• Inode: – Inode number is a unique number for each file
which is used for the internal maintenance by the file
system.
• Links: 1 – Number of links to the file
• Access: ( 0644/-rw-r--r-- ): Access specifier displayed in both
octal and character format. Let us see explanation about
both the format.
• Uid: (0/ root) – File owner’s user id and user name are
displayed.
• Gid: (0/ root) – File owner’s group id and group name are
displayed.
• Access: Last access time of the file.
• Modify: Last modification time of the file.
• Change: Last change time of the inode data of that file.
Viewing file properties using stat and ls -li command as follows
root@Troy:~# ls -il hardware.txt
15470100 -rw-r--r-- 1 root root 14877 Jul 22 20:51 hardware.txt
First column shows inode number
Create file
touch filename; will create empty files
cat > filename; will create file and prompt you to enter the text
use CTRL+C[Enter] to save the file;it will overwrite filename if
it is already there
cat >> filename; use this to append the data to a fileRemove files
The rm command is used for removing files and directories. To
remove a file:
$ rm file
If you use the -i option, you'll be prompted before removing the
file:
$ rm -i file
You can also delete more files at once:
rm file1 file2
Creating directories
mkdir directory_name
mkdir arvind;will create a directory namely arvind
rm -r directory_name
Copying
To copy files, you use the cp command. The following will copy
file to file2. Note that if file2 doesn't exist, it'll be
created, but if it exists, it'll be overwritten:
$ cp file file2
There aren't any undo commands in the Linux CLI, so accidentally
overwriting an important file would probably make you pull your
head off. The risk of doing so is smaller if you use the -i
option ("interactive") with cp. The following does the same as
the above, but if file2 exists, you'll be prompted before
overwriting:
$ cp -i file file2
cp: overwrite `file2'? n
$
So it's a good idea to use the -i option whenever you're dealingwith important files you don't want to lose!
If you want to copy file into directory dir1:
$ cp file dir1
The following would do the same as the above, copy file into
dir1, but under a different name:
$ cp file dir1/file2
You can also copy multiple files into one directory with a
single command:
$ cp file1 file2 file3 dir1
Note that if the last argument isn't a directory name, you'll
get an error message complaining about it.
Moving and renaming
The mv command can be used for moving or renaming files. To
rename a file, you can use it like this:
$ mv file file2
If file2 doesn't exist, it'll be created, but if it exists,
it'll be overwritten. If you want to be prompted before
overwriting files, you can use the -i option the same way as
with cp:
$ mv -i file file2
mv: overwrite `file2'? y
To move the file into another directory:
$ mv file dir1
If you want to rename the file to file2 and move it into another
directory, you probably already figured out the command:
$ mv file dir1/file2
root@Troy:~# whatis grep find locate which
grep - print lines matching a pattern
find - search for files in a directory hierarchy
locate - find files by name
which - locate a commandgrep command
Search for the given string in a single file
grep "literal_string" filename
Checking for the given string in multiple files.
Syntax:
grep "string" FILE_PATTERN
Case insensitive search using grep -i
Syntax:
grep -i "string" FILE
This is also a basic usage of the grep. This searches for the given
string/pattern case insensitively.
Checking for full words, not for sub-strings using grep -w
If you want to search for a word, and to avoid it to match the
substrings use -w option. Just doing out a normal search will
show out all the lines.
The following example is the regular grep where it is searching
for “is”. When you search for “is”, without any option it will
show out “is”, “his”, “this” and everything which has the
substring “is”.
The following example is the WORD grep where it is searching
only for the word “is”.
grep -iw "is" demo_file

Invert match using grep -v
When you want to display the lines which does not matches the
given string/pattern, use the option -v as shown below. This
example will display all the lines that did not match the word
“go”.
grep -v "go" demo_textdisplay the lines which does not matches all the given pattern.
Syntax:
grep -v -e "pattern" -e "pattern"
Counting the number of matches using grep -c
When you want to count that how many lines matches the given
pattern/string, then use the option -c.
Syntax:
grep -c "pattern" filename
When you want to find out how many lines that does not match the
pattern
grep -v -c "pattern" filename
Display only the file names which matches the given pattern using
grep –l
If you want the grep to show out only the file names which
matched the given pattern, use the -l (lower-case L) option.
When you give multiple files to the grep as input, it displays
the names of file which contains the text that matches the
pattern, will be very handy when you try to find some notes in
your whole directory structure.
$ grep -l this demo_*
demo_file
demo_file1
Show line number while displaying the output using grep –n
#grep -n “string” file_name
Displaying lines before/after/around the match using grep -A, -B
and -C
When doing a grep on a huge file, it may be useful to see some
lines after the match. You might feel handy if grep can show you
not only the matching lines but also the lines
after/before/around the match.Please create the following demo_text file for this example.
$ cat demo_text
4. Vim Word Navigation
You may want to do several navigation in relation to the words,
such as:
*
*
*
*
*
*
e
E
b
B
w
W
-
-
-
-
-
-
go
go
go
go
go
go
to
to
to
to
to
to
the
the
the
the
the
the
end of the current word.
end of the current WORD.
previous (before) word.
previous (before) WORD.
next word.
next WORD.
WORD - WORD consists of a sequence of non-blank characters,
separated with white space.
word - word consists of a sequence of letters, digits and
underscores.
Example to show the difference between WORD and word
* 192.168.1.1 - single WORD
* 192.168.1.1 - seven words.
6.1 Display N lines after match
-A is the option which prints the specified N lines after the
match as shown below.
Syntax:
grep -A <N> "string" FILENAME
The following example prints the matched line, along with the 3
lines after it.
$ grep -A 3 -i "example" demo_text
Example to show the difference between WORD and word
* 192.168.1.1 - single WORD
* 192.168.1.1 - seven words.
6.2 Display N lines before match-B is the option which prints the specified N lines before the
match.
Syntax:
grep -B <N> "string" FILENAME
When you had option to show the N lines after match, you have
the -B option for the opposite.
$ grep -B 2 "single WORD" demo_text
Example to show the difference between WORD and word
* 192.168.1.1 - single WORD
6.3 Display N lines around match
-C is the option which prints the specified N lines before the
match. In some occasion you might want the match to be appeared
with the lines from both the side. This options shows N lines in
both the side(before & after) of match.
$ grep -C 2 "Example" demo_text
word - word consists of a sequence of letters, digits and
underscores.
Example to show the difference between WORD and word
* 192.168.1.1 - single WORD
Match regular expression in files
Syntax:
grep "REGEX" filename
This is a very powerful feature, if you can use use regular
expression effectively. In the following example, it searches
for all the pattern that starts with “lines” and ends with
“empty” with anything in-between. i.e To search “lines[anything
in-between]empty” in the demo_file.
$ grep "lines.*empty" demo_file
Two lines above this line is empty.
From documentation of grep: A regular expression may be followedby one of several repetition operators:
•
•
•
•
•
•
•
? The preceding item is optional and matched at most once.
* The preceding item will be matched zero or more times.
+ The preceding item will be matched one or more times.
{n} The preceding item is matched exactly n times.
{n,} The preceding item is matched n or more times.
{,m} The preceding item is matched at most m times.
{n,m} The preceding item is matched at least n times, but
not more than m times.
Example 1. Beginning of line ( ^ )
In grep command, caret Symbol ^ matches the expression at the
start of a line. In the following example, it displays all the
line which starts with the Nov 10. i.e All the messages logged
on November 10.
$ grep "^Nov 10" messages.1
Nov
Nov
Nov
Nov
Nov
Nov
10
10
10
10
10
10
01:12:55
01:17:17
01:18:49
13:21:26
13:25:46
13:26:27
gs123
gs123
gs123
gs123
gs123
gs123
ntpd[2241]:
ntpd[2241]:
ntpd[2241]:
ntpd[2241]:
ntpd[2241]:
ntpd[2241]:
time reset +0.177479 s
synchronized to LOCAL(0), stratum 10
synchronized to 15.1.13.13, stratum 3
time reset +0.146664 s
synchronized to LOCAL(0), stratum 10
synchronized to 15.1.13.13, stratum 3
The ^ matches the expression in the beginning of a line, only if
it is the first character in a regular expression. ^N matches
line beginning with N.
Example 2. End of the line ( $)
Character $ matches the expression at the end of a line. The
following command will help you to get all the lines which ends
with the word “terminating”.
$ grep "terminating.$" messages
Jul 12 17:01:09 cloneme kernel: Kernel log daemon terminating.
Oct 28 06:29:54 cloneme kernel: Kernel log daemon terminating.
From the above output you can come to know when all the kernel
log has got terminated. Just like ^ matches the beginning of the
line only if it is the first character, $ matches the end of the
line only if it is the last character in a regular expression.Example 3. Count of empty lines ( ^$ )
Using ^ and $ character you can find out the empty lines
available in a file. “^$” specifies empty line.
$ grep -c "^$" messages anaconda.log
messages:0
anaconda.log:3
The above commands displays the count of the empty lines
available in the messages and anaconda.log files.
Example 4. Single Character (.)
The special meta-character “.” (dot) matches any character
except the end of the line character. Let us take the input file
which has the content as follows.
$ cat input
1. first line
2. hi hello
3. hi zello how are you
4. cello
5. aello
6. eello
7. last line
Now let us search for a word which has any single character
followed by ello. i.e hello, cello etc.,
$ grep ".ello" input
2. hi hello
3. hi zello how are you
4. cello
5. aello
6. eello
In case if you want to search for a word which has only 4
character you can give grep -w “....” where single dot represents
any single character.
Example 5. Zero or more occurrence (*)
The special character “*” matches zero or more occurrence of the
previous character. For example, the pattern ’1*’ matches zero
or more ’1′.The following example searches for a pattern “kernel: *” i.e
kernel: and zero or more occurrence of space character.
$ grep "kernel: *." *
messages.4:Jul 12 17:01:02 cloneme kernel: ACPI: PCI interrupt
for device 0000:00:11.0 disabled
messages.4:Oct 28 06:29:49 cloneme kernel: ACPI: PM-Timer IO
Port: 0x1008
messages.4:Oct 28 06:31:06 btovm871 kernel: sda: sda1 sda2 sda3
messages.4:Oct 28 06:31:06 btovm871 kernel: sd 0:0:0:0: Attached
scsi disk sda
.
.
In the above example it matches for kernel and colon symbol
followed by any number of spaces/no space and “.” matches any
single character.
Example 6. One or more occurrence (\+)
The special character “\+” matches one or more occurrence of the
previous character. ” \+” matches at least one or more space
character.
If there is no space then it will not match. The character “+”
comes under extended regular expression. So you have to escape
when you want to use it with the grep command.
$ cat input
hi hello
hi
hello how are you
hihello
$ grep "hi \+hello" input
hi hello
hi
hello how are you
In the above example, the grep pattern matches for the pattern
‘hi’, followed by one or more space character, followed by
“hello”.
If there is no space between hi and hello it wont match that.
However, * character matches zero or more occurrence.
“hihello” will be matched by * as shown below.
$ grep "hi *hello" input
hi hellohi
hello how are you
hihello
Example 7. Zero or one occurrence (\?)
The special character “?” matches zero or one occurrence of the
previous character. “0?” matches single zero or nothing.
$ grep "hi \?hello" input
hi hello
hihello
“hi \?hello” matches hi and hello with single space (hi hello)
and no space (hihello).
The line which has more than one space between hi and hello did
not get matched in the above command.
Example 8.Escaping the special character (\)
If you want to search for special characters (for example: * ,
dot) in the content you have to escape the special character in
the regular expression.
$ grep "127\.0\.0\.1" /var/log/messages.4
Oct 28 06:31:10 btovm871 ntpd[2241]: Listening on interface lo,
127.0.0.1#123 Enabled
Example 9. Character Class ([0-9])
The character class is nothing but list of characters mentioned
with in the square bracket which is used to match only one out
of several characters.
$ grep -B 1 "[0123456789]\+ times" /var/log/messages.4
Oct 28 06:38:35
Oct 28 06:38:35
Oct 28 06:38:38
0 Not Found
Oct 28 06:38:38
btovm871 init: open(/dev/pts/0): No such file or directory
btovm871 last message repeated 2 times
btovm871 pcscd: winscard.c:304:SCardConnect() Reader E-Gate 0
btovm871 last message repeated 3 times
Repeated messages will be logged in messages logfile as “last
message repeated n times”. The above example searches for the
line which has any number (0to9) followed by the word “times”.
If it matches it displays the line before the matched line and
matched line also.
With in the square bracket, using hyphen you can specify therange of characters. Like [0123456789] can be represented by [0-
9]. Alphabets range also can be specified such as [a-z],[A-Z]
etc. So the above command can also be written as
$ grep -B 1 "[0-9]\+ times" /var/log/messages.4
Example 10. Exception in the character class
If you want to search for all the characters except those in the
square bracket, then use ^ (Caret) symbol as the first character
after open square bracket. The following example searches for a
line which does not start with the vowel letter from dictionary
word file in linux.
$ grep -i
1080
10-point
10th
11-point
12-point
16-point
18-point
1st
2
"^[^aeiou]" /usr/share/dict/linux.words
First caret symbol in regular expression represents beginning of
the line. However, caret symbol inside the square bracket
represents “except” — i.e match except everything in the square
bracket.
OR Operation (|)
Pipe character (|) in grep is used to specify that either of two
whole subexpressions occur in a position. “subexpression1|
subexpression2′′ matches either subexpression1 or subexpression2.
The following example will remove three various kind of comment
lines in a file using OR in a grep command.
First, create a sample file called “comments”.
$ cat comments
This file shows the comment character in various
programming/scripting languages
### Perl / shell scriptingIf the Line starts with single hash symbol,
then its a comment in Perl and shell scripting.
' VB Scripting comment
The line should start with a single quote to comment in VB
scripting.
// C programming single line comment.
Double slashes in the beginning of the line for single line
comment in C.
The file called “comments” has perl,VB script and C programming
comment lines. Now the following grep command searches for the
line which does not start with # or single quote (‘) or double
front slashes (//).
$ grep -v "^#\|^'\|^\/\/" comments
root@Troy:~# egrep -v "^#|^'|^//" test.txt
This file shows the comment character in various
programming/scripting languages
If the Line starts with single hash symbol,
then its a comment in Perl and shell scripting.
The line should start with a single quote to comment in VB
scripting.
Double slashes in the beginning of the line for single line
comment in C.
Character class expression
As we have seen in our previous regex article example 9, list of
characters can be mentioned with in the square brackets to match
only one out of several characters. Grep command supports some
special character classes that denote certain common ranges. Few
of them are listed here. Refer man page of grep to know various
character class expressions.
[:digit:]
[:alnum:]
to z.
[:alpha:]
[:blank:]
Only the digits 0 to 9
Any alphanumeric character 0 to 9 OR A to Z or a
Any alpha character A to Z or a to z.
Space and TAB characters only.
These are always used inside square brackets in the form
[[:digit:]]. Now let us grep all the process Ids of ntpd daemon
process using appropriate character class expression.$ grep -e "ntpd\[[[:digit:]]\+\]" /var/log/messages.4
Oct
Oct
Oct
Oct
Oct
28
28
28
28
29
11:42:20
11:42:20
12:33:31
12:50:46
07:55:29
gstuff1
gstuff1
gstuff1
gstuff1
gstuff1
ntpd[2241]:
ntpd[2241]:
ntpd[2241]:
ntpd[2241]:
ntpd[2241]:
synchronized to LOCAL(0), stratum 10
synchronized to 15.11.13.123, stratum 3
synchronized to LOCAL(0), stratum 10
synchronized to 15.11.13.123, stratum 3
time reset -0.180737 s
M to N occurences ({m,n})
A regular expression followed by {m,n} indicates that the
preceding item is matched at least m times, but not more than n
times. The values of m and n must be non-negative and smaller
than 255.
The following example prints the line if its in the range of 0
to 99999.
$ cat number
12
12345
123456
19816282
$ grep
12
12345
"^[0-9]\{1,5\}$" number
The file called “number” has the list of numbers, the above grep
command matches only the number which 1 (minimum is 0) to 5
digits (maximum 99999).
Example 4. Exact M occurence ({m})
A Regular expression followed by {m} matches exactly m
occurences of the preceding expression. The following grep
command will display only the number which has 5 digits.
$ grep
12345
"^[0-9]\{5\}$" number
Back references (\n)Grouping the expressions for further use is available in grep
through back-references. For ex, \([0-9]\)\1 matches two digit
number in which both the digits are same number like 11,22,33
etc.,
# grep -e '^\(abc\)\1$'
abc
abcabc
abcabc
In the above grep command, it accepts the input the STDIN. when
it reads the input “abc” it didnt match, The line “abcabc”
matches with the given expression so it prints. If you want to
use Extended regular expression its always preferred to use
egrep command. grep with -e option also works like egrep, but
you have to escape the special characters like paranthesis
root@Troy:~# egrep '^(abc)\1$' test.txt
abcabc
abcabc
Match the pattern “Object Oriented”
So far we have seen different tips in grep command, Now using
those tips, let us match “object oriented” in various formats.
root@Troy:~# grep "OO\|\([oO]bject\( \|\-\)[oO]riented\)"
test.txt
OO
object Oriented
Object oriented
root@Troy:~# egrep "OO|([oO]bject( |-)[oO]riented)" test.txt
OO
object Oriented
Object oriented
The above grep command matches the “OO”, “object oriented”,
“Object-oriented” and etc.,
Print the line “vowel singlecharacter samevowel”
The following grep command print all lines containing a vowel(a, e, i, o, or u) followed by a single character followed by
the same vowel again. Thus, it will find eve or adam but not
vera.
$ cat input
evening
adam
vera
$ grep "\([aeiou]\).\1" input
evening
adam
root@Troy:~# egrep "([aeiou]).\1" test.txt
evening
adam
How to use Find command
Find Files Using Name
This is a basic usage of the find command. This example finds
all files with name — MyCProgram.c in the current directory and
all its sub-directories.
# find -name "MyCProgram.c"
Find Files Using Name and Ignoring Case
# find -iname "MyCProgram.c"
Executing Commands on the Files Found by the Find Command.
In the example below, the find command calculates the md5sum of
all the files with the name MyCProgram.c (ignoring case). {} is
replaced by the current file name.
# find -iname "MyCProgram.c" -exec md5sum {} \;
The following command removes *.zip files that are over 100M.
#find / -type f -name *.zip -size +100M -exec rm -i {} \;"
Limit Search To Specific Directory Level Using mindepth and
maxdepthFind the passwd file under all sub-directories starting from
root directory.
# find / -name passwd
Find the passwd file under root and one level down. (i.e root —
level 1, and one sub-directory — level 2)
# find / -maxdepth 2 -name passwd
Find the passwd file under root and two levels down. (i.e root —
level 1, and two sub-directories — level 2 and 3 )
# find / -maxdepth 3 -name passwd
Find the password file between sub-directory level 2 and 4.
# find -mindepth 3 -maxdepth 5 -name passwd
Inverting the match
Shows the files or directories whose name are not
MyCProgram.c .Since the maxdepth is 1, this will look only under
current directory.
#find -maxdepth 1 -not -iname "MyCProgram.c"
#find . -maxdepth 1 -type f -not -iname "rahul" -a -not -name
".*"
Find file based on the File-Permissions
Following operations are possible.
• Find files that match exact permission
• Check whether the given permission matches, irrespective of
other permission bits
• Search by giving octal / symbolic representation
For this example, let us assume that the directory contains the
following files. Please note that the file-permissions on these
files are different.
# ls -l
total 0
-rwxrwxrwx 1 root root 0 2009-02-19 20:31 all_for_all
-rw-r--r-- 1 root root 0 2009-02-19 20:30 everybody_read
---------- 1 root root 0 2009-02-19 20:31 no_for_all-rw------- 1 root root 0 2009-02-19 20:29 ordinary_file
-rw-r----- 1 root root 0 2009-02-19 20:27 others_can_also_read
----r----- 1 root root 0 2009-02-19 20:27 others_can_only_read
Find files which has read permission to group. Use the following
command to find all files that are readable by the group in your
home directory, irrespective of other permissions for that file.
# find . -perm -g=r -type f -exec ls -l {} \;
-rw-r--r-- 1 root root 0 2009-02-19 20:30 ./everybody_read
-rwxrwxrwx 1 root root 0 2009-02-19 20:31 ./all_for_all
----r----- 1 root root 0 2009-02-19 20:27 ./others_can_only_read
-rw-r----- 1 root root 0 2009-02-19 20:27 ./others_can_also_read
Find files which has read permission only to group.
# find . -perm g=r -type f -exec ls -l {} \;
----r----- 1 root root 0 2009-02-19 20:27 ./others_can_only_read
Find files which has read permission only to group [ search by
octal ]
# find . -perm 040 -type f -exec ls -l {} \;
----r----- 1 root root 0 2009-02-19 20:27 ./others_can_only_read
Find all empty files (zero byte file) in your home directory and
its subdirectory
Most files of the following command output will be lock-files
and place holders created by other applications.
# find ~ -empty
List all the empty files only in your home directory.
# find . -maxdepth 1 -empty
List only the non-hidden empty files only in the current
directory.
# find . -maxdepth 1 -empty -not -name ".*"
Find Files Based on file-type using option -type
Find only the socket files.
# find . -type sFind all directories
# find . -type d
Find only the normal files
# find . -type f
Find all the hidden files
# find . -type f -name ".*"
Find all the hidden directories
# find . -type d -name ".*"
Find Files by Size
Using the -size option you can find files by size.
Find files bigger than the given size
# find ~ -size +100M
Find files smaller than the given size
# find ~ -size -100M
Find files that matches the exact given size
# find ~ -size 100M
Note: – means less than the give size, + means more than the
given size, and no symbol means exact given size.
Finding Files by its inode Number.
Every file has an unique inode number, using that we can
identify that file. Create two files with similar name. i.e one
file with a space at the end.
# touch "test-file-name"
# touch "test-file-name "
[Note: There is a space at the end]
# ls -1 test*
test-file-name
test-file-name
From the ls output, you cannot identify which file has the spaceat the end. Using option -i, you can view the inode number of
the file, which will be different for these two files.
# ls -i1 test*
16187429 test-file-name
16187430 test-file-name
You can specify inode number on a find command as shown below.
In this example, find command renames a file using the inode
number.
# find -inum 16187430 -exec mv {} new-test-file-name \;
# ls -i1 *test*
16187430 new-test-file-name
16187429 test-file-name
You can use this technique when you want to do some operation
with the files which are named poorly as shown in the example
below. For example, the file with name — file?.txt has a special
character in it. If you try to execute “rm file?.txt”, all the
following three files will get removed. So, follow the steps
below to delete only the “file?.txt” file.
# ls
file1.txt
file2.txt
file?.txt
Find the inode numbers of each file.
# ls -i1
804178 file1.txt
804179 file2.txt
804180 file?.txt
Use the inode number to remove the file that had special
character in it as shown below.
# find -inum 804180 -exec rm {} \;
# ls
file1.txt file2.txt
[Note: The file with name "file?.txt" is now removed]or you can use rm -i file*
Finding the Top 5 Big Files
The following command will display the top 5 largest file in the
current directory and its subdirectory. This may take a while to
execute depending on the total number of files the command has
to process.
# find . -type f -exec ls -s {} \; | sort -n -r | head -5
10. Finding the Top 5 Small Files
Technique is same as finding the bigger files, but the only
difference the sort is ascending order.
# find . -type f -exec ls -s {} \; | sort -n
| head -5
In the above command, most probably you will get to see only the
ZERO byte files ( empty files ). So, you can use the following
command to list the smaller files other than the ZERO byte files.
#find . -not -empty -type f -exec ls -s {} \; | sort -n | head -5
Find files by comparing with the modification time of other file.
Show files which are modified after the specified file. The
following find command displays all the files that are
created/modified after ordinary_file.
# ls -lrt
total 0
-rw-r-----
----r-----
-rw-------
-rw-r--r--
-rwxrwxrwx
----------
1
1
1
1
1
1
root
root
root
root
root
root
root
root
root
root
root
root
0
0
0
0
0
0
2009-02-19
2009-02-19
2009-02-19
2009-02-19
2009-02-19
2009-02-19
20:27
20:27
20:29
20:30
20:31
20:31
# find -newer ordinary_file
.
./everybody_read
./all_for_all
./no_for_all
Create Alias for Frequent Find Operations
others_can_also_read
others_can_only_read
ordinary_file
everybody_read
all_for_all
no_for_allIf you find some thing as pretty useful, then you can make it as
an alias. And execute it whenever you want.
Remove the files named a.out frequently.
# alias rmao="find . -iname a.out -exec rm {} \;"
# rmao
Remove the core files generated by c program.
# alias rmc="find . -iname core -exec rm {} \;"
# rmc
Remove big archive files using find command
The following command removes *.zip files that are over 100M.
# find / -type f -name *.zip -size +100M -exec rm -i {} \;"
Remove all *.tar file that are over 100M using the alias rm100m
(Remove 100M). Use the similar concepts and create alias like
rm1g, rm2g, rm5g to remove file size greater than 1G, 2G and 5G
respectively.
#alias
#alias
#alias
#alias
#
#
#
#
rm100m="find / -type f -name
rm1g="find / -type f -name
rm2g="find / -type f -name
rm5g="find / -type f -name
*.tar
*.tar
*.tar
*.tar
-size
-size
-size
-size
+100M -exec rm -i {} \;"
+1G -exec rm -i {} \;"
+2G -exec rm -i {} \;"
+5G -exec rm -i {} \;"
rm100m
rm1g
rm2g
rm5g
Find Files Based on Access / Modification / Change Time
You can find files based on following three file time attribute.
1. Access time of the file. Access time gets updated when the
file accessed.
2. Modification time of the file. Modification time gets
updated when the file content modified.
3. Change time of the file. Change time gets updated when the
inode data changes.
In the following examples, the difference between the min option
and the time option is the argument.• min argument treats its argument as minutes. For example,
min 60 = 60 minutes (1 hour).
• time argument treats its argument as 24 hours. For example,
time 2 = 2*24 hours (2 days).
• While doing the 24 hours calculation, the fractional parts
are ignored so 25 hours is taken as 24 hours, and 47 hours
is also taken as 24 hours, only 48 hours is taken as 48
hours. To get more clarity refer the -atime section of the
find command man page.
Example 1: Find files whose content got updated within last 1
hour
To find the files based upon the content modification time, the
option -mmin, and -mtime is used. Following is the definition of
mmin and mtime from man page.
• -mmin n File’s data was last modified n minutes ago.
• -mtime n File’s data was last modified n*24 hours ago.
Following example will find files in the current directory and
sub-directories, whose content got updated within last 1 hour
(60 minutes)
# find . -mmin -60
In the same way, following example finds all the files (under
root file system /) that got updated within the last 24 hours (1
day).
# find / -mtime -1
Example 2: Find files which got accessed before 1 hour
To find the files based up on the file access time, the option
-amin, and -atime is used. Following is the definition of amin
and atime from find man page.
•
-amin n File was last accessed n minutes ago
• -atime n File was last accessed n*24 hours ago
Following example will find files in the current directory and
sub-directories, which got accessed within last 1 hour (60
minutes)# find -amin -60
In the same way, following example finds all the files (under
root file system /) that got accessed within the last 24 hours
(1 day).
# find / -atime -1
Example 3: Find files which got changed exactly before 1 hour
To find the files based up on the file inode change time, the
option -cmin, and -ctime is used. Following is the definition of
cmin and ctime from find man page.
• -cmin n File’s status was last changed n minutes ago.
• -ctime n File’s status was last changed n*24 hours ago.
Following example will find files in the current directory and
sub-directories, which changed within last 1 hour (60 minutes)
# find . -cmin -60
In the same way, following example finds all the files (under
root file system /) that got changed within the last 24 hours (1
day).
# find / -ctime -1
Restricting the find output only to files.
(Display only files as find command results)
The above find command’s will also show the directories because
directories gets accessed when the file inside it gets accessed.
But if you want only the files to be displayed then give -type f
in the find command as
The following find command displays files that are accessed in
the last 30 minutes.
# find /etc/sysconfig -amin -30
.
./console
./network-scripts
./i18n./rhn
./rhn/clientCaps.d
./networking
./networking/profiles
./networking/profiles/default
./networking/profiles/default/resolv.conf
./networking/profiles/default/hosts
./networking/devices
./apm-scripts
[Note: The above output contains both files and directories]
# find /etc/sysconfig -amin -30 -type f
./i18n
./networking/profiles/default/resolv.conf
./networking/profiles/default/hosts
[Note: The above output contains only files]
Example 5: Restricting the search only to unhidden files. (Do
not display hidden files in find output)
When we don’t want the hidden files to be listed in the find
output, we can use the following regex.
The below find displays the files which are modified in the last
15 minutes. And it lists only the unhidden files. i.e hidden
files that starts with a . (period) are not displayed in the
find output.
# find . -mmin -15 \( ! -regex ".*/\..*" \)
Finding Files Comparatively Using Find Command
Human mind can remember things better by reference such as, i
want to find files which i edited after editing the file “test”.
You can find files by referring to the other files modification
as like the following.
Find files which are modified after modification of a particular FILE
Syntax: find -newer FILE
Following example displays all the files which are modified
after the /etc/passwd files was modified. This is helpful, if
you want to track all the activities you’ve done after adding anew user.
# find -newer /etc/passwd
Find files which are accessed after modification of a specific
FILE
Syntax: find -anewer FILE
Following example displays all the files which are accessed
after modifying /etc/hosts. If you remember adding an entry to
the /etc/hosts and would like to see all the files that you’ve
accessed since then, use the following command.
# find -anewer /etc/hosts
Example 8: Find files whose status got changed after the
modification of a specific FILE.
Syntax: find -cnewer FILE
Following example displays all the files whose status got
changed after modifying the /etc/fstab. If you remember adding a
mount point in the /etc/fstab and would like to know all the
files who status got changed since then, use the following
command.
find -cnewer /etc/fstab
Perform Any Operation on Files Found From Find Command
This section explains about how to do different operation on the
files from the find command. i.e how to manipulate the files
returned by the find command output.
We can specify any operation on the files found from find
command.
find <CONDITION to Find files> -exec <OPERATION> \;
The OPERATION can be anything such as:
• rm command to remove the files found by find command.• mv command to rename the files found.
• ls -l command to get details of the find command output
files.
• md5sum on find command output files
• wc command to count the total number of words on find
command output files.
• Execute any Unix shell command on find command output files.
• or Execute your own custom shell script / command on find
command output files.
ls -l in find command output. Long list the files which are
edited within the last 1 hour.
# find -mmin -60
./cron
./secure
# find -mmin -60 -exec ls -l {} \;
-rw------- 1 root root 1028 Jun 21 15:01 ./cron
-rw------- 1 root root 831752 Jun 21 15:42 ./secure
Example 10: Searching Only in the Current Filesystem
System administrators would want to search in the root file
system, but not in the other mounted partitions. When you have
multiple partitions mounted, and if you want to search in /. You
can do the following.
Following command will search for *.log files starting from /.
i.e If you have multiple partitions mounted under / (root), the
following command will search all those mounted partitions.
# find / -name "*.log"
This will search for the file only in the current file system.
Following is the xdev definition from find man page:
• -xdev Don’t descend directories on other filesystems.
Following command will search for *.log files starting from /
(root) and only in the current file system. i.e If you have
multiple partitions mounted under / (root), the following
command will NOT search all those mounted partitions.
# find / -xdev -name "*.log"Example 11: Using more than one { } in same command
Manual says only one instance of the {} is possible. But you can
use more than one {} in the same command as shown below.
# find -name "*.txt" cp {} {}.bkup \;
Using this {} in the same command is possible but using it in
different command it is not possible, say you want to rename the
files as following, which will not give the expected result.
find -name "*.txt" -exec mv {} `basename {} .htm`.html \;
Example 12: Using { } in more than one instance.
You can simulate it by writing a shell script as shown below.
# mv "$1" "`basename "$1" .htm`.html"
These double quotes are to handle spaces in file name. And then
call that shell script from the find command as shown below.
find -name "*.html" -exec ./mv.sh '{}' \;
So for any reason if you want the same file name to be used more
than once then writing the simple shell script and passing the
file names as argument is the simplest way to do it.
Redirecting errors to /dev/null
Redirecting the errors is not a good practice. An experienced
user understands the importance of getting the error printed on
terminal and fix it.
Particularly in find command redirecting the errors is not a
good practice. But if you don’t want to see the errors and would
like to redirect it to null do it as shown below.
find -name "*.txt" 2>>/dev/null
Sometimes this may be helpful. For example, if you are trying to
find all the *.conf file under / (root) from your account, you
may get lot of “Permission denied” error message as shown below.
$ find / -name "*.conf"
/sbin/generate-modprobe.conffind: /tmp/orbit-root: Permission denied
find: /tmp/ssh-gccBMp5019: Permission denied
find: /tmp/keyring-5iqiGo: Permission denied
find: /var/log/httpd: Permission denied
find: /var/log/ppp: Permission denied
/boot/grub/grub.conf
find: /var/log/audit: Permission denied
find: /var/log/squid: Permission denied
find: /var/log/samba: Permission denied
find: /var/cache/alchemist/printconf.rpm/wm: Permission denied
[Note: There are two valid *.conf files burned in the
"Permission denied" messages]
So, if you want to just view the real output of the find command
and not the “Permission denied” error message you can redirect
the error message to /dev/null as shown below.
$ find / -name "*.conf" 2>>/dev/null
/sbin/generate-modprobe.conf
/boot/grub/grub.conf
[Note: All the "Permission denied" messages are not displayed]
Example 14: Substitute space with underscore in the file name.
Audio files you download from internet mostly come with the
spaces in it. But having space in the file name is not so good
for Linux kind of systems. You can use the find and rename
command combination as shown below to rename the files, by
substituting the space with underscore.
The following replaces space in all the *.mp3 files with _
$find . -type f -iname “*.mp3′′ -exec rename “s/ /_/g” {} \;
#find . -maxdepth 1 -type f -iname "*.yaml" -exec rename "s/
/_/g" {} \;
Executing two find commands at the same time
As shown in the examples of the find command in its manual page,
the following is the syntax which can be used to execute two
commands in single traversal.
The following find command example, traverse the filesystem just
once, listing setuid files and directories into /root/suid.txtand large files into /root/big.txt.
#find /
\( -perm -4000 -fprintf /root/suid.txt '%#m %u
%p\n' \) , \
\( -size +100M -fprintf /root/big.txt '%-10s %p\n' \)
[syed@test ~]$ whatis which locate
which
(1)
- shows the full path of (shell) commands
which
(rpm) - Displays where a particular program in your path is
located.
locate
(1)
- find files by name
Eg. [syed@test ~]$ which ls
alias ls='ls --color=tty'
/bin/ls
Is showing where ls lies
[syed@test ~]$ locate txt1
/home/syed/txt1View File Content – less, more, tail, head; Symbolic and Hard
Links mechanism
The main advantage of using "less" is that you can reverse scroll
through a file and you don't need to wait for "less" to load the
whole file into memory before you can start to view it.
Less Command – Search Navigation
Once you’ve opened a log file (or any file) using less file-
name, use the following keys to search. Please note that the
match will be highlighted automatically by default.
Forward Search
• / – search for a pattern which will take you to the next
occurrence.
• n – for next match in forward
• N – for previous match in backward
Backward Search
• ? – search for a pattern which will take you to the previous
occurrence.
• n – for next match in backward direction
• N – for previous match in forward direction
Tip: If you dont bother about which direction the search is
happening, and you want to search file path, or URL, such as
“/home/ramesh/”, you can use backward search (?pattern) which
will be handy as you don’t want to escape slashes each time.
Search Path
In forward: /\/home\/ramesh\/
In backward: ?/home/ramesh/
Simulate tail -f inside less pager – Press F
Once you’ve opened a file using less command, any content that
is appended to the file after that will not be displayed
automatically. However, you can press F less command will show
the status ‘waiting for data‘. This is as similar to ‘tail -f’.
Less Command – Other Navigations
The following are other navigation operations that you can use
inside the less pager.
G – go to the end of file
• g – go to the start of file
• q or ZZ – exit the less pagerOther useful Less Command Operations
• v – using the configured editor edit the current file.
• h – summary of less commands
• &pattern – display only the matching lines, not all.
more (1)
- file perusal filter for crt viewing
more filename
then type h for other options
head (1) - output the first part of files
tail (1) - output the last part of files
by default head shows first 10 lines and tail shows last 10 lines
head -n5 file ;will show first 5 line
tail -n5 file;will show last 5 line
How to create a hard link?
ln monu arvind
monu and arvind both are two files having the same inode as shown
in yellow color and number of link as shown in grey color
root@Troy:~# ls -li arvind Monu
15467152 -rw-r--r-- 2 root root 13 Jul 24 20:01 arvind
15467152 -rw-r--r-- 2 root root 13 Jul 24 20:01 Monu
How to create a symbolic link
ln -s /home/arvind/singh
/home/arvind/Documents/arvind
root@Troy:~/Documents# ls -li arvind
15466774 lrwxrwxrwx 1 root root 18 Jul 24 20:06 arvind -> /home/arvind/singh4.
File attributes - Changing user and group
ownership, permissions e.g. chmod, chown etc
Change the owner of a file
# ls -lart tmpfile
-rw-r--r-- 1 himanshu family 0 2012-05-22 20:03 tmpfile
# chown root tmpfile
# chgrp developer tmpfile
# ls -l tmpfile
-rw-r--r-- 1 root developer
0 2012-05-22 20:03 tmpfile
So we see that the owner of the file was changed from ‘himanshu’ to
‘root’.
Change the group of a file
Through the chown command, the group (that a file belongs to)
can also be changed
# ls -l tmpfile
-rw-r--r-- 1 himanshu family 0 2012-05-22 20:03 tmpfile
# chown :friends tmpfile
# ls -l tmpfile
-rw-r--r-- 1 himanshu friends 0 2012-05-22 20:03 tmpfile
If you observe closely, the group of the file changed from ‘family’ to
‘friends’. So we see that by just adding a ‘:’ followed by the new
group name, the group of the file can be changed.
Change both owner and the group
# ls -l tmpfile
-rw-r--r-- 1 root family 0 2012-05-22 20:03 tmpfile
# chown himanshu:friends tmpfile
# ls -l tmpfile
-rw-r--r-- 1 himanshu friends 0 2012-05-22 20:03 tmpfile
So we see that using the syntax ‘<newOwner>:<newGroup>’, the
owner as well as group can be changed in one go.Using chown command on symbolic link file
Here is a symbolic link :
# ls -l tmpfile_symlnk
lrwxrwxrwx 1 himanshu family 7 2012-05-22 20:03 tmpfile_symlnk -> tmpfile
So we see that the symbolic link ‘tmpfile_symlink’ links to the file ‘tmpfile’.
Lets see what happens if chown command is issued on a symbolic link:
# chown root:friends tmpfile_symlnk
# ls -l tmpfile_symlnk
lrwxrwxrwx 1 himanshu family 7 2012-05-22 20:03 tmpfile_symlnk -> tmpfile
# ls -l tmpfile
-rw-r--r-- 1 root friends 0 2012-05-22 20:03 tmpfile
When the chown command was issued on symbolic link to change the owner
as well as the group then its the referent of the symbolic link ie
‘tmpfile’ whose owner and group got changed. This is the default
behavior of the chown command. Also, there exists a flag ‘–
dereference’ for the same.
Using chown command to forcefully change the owner/group of
symbolic file.
Using flag ‘-h’, you can forcefully change the owner or group of
a symbolic link as shown below.
# ls -l tmpfile_symlnk
lrwxrwxrwx 1 himanshu family 7 2012-05-22 20:03 tmpfile_symlnk -> tmpfile
# chown -h root:friends tmpfile_symlnk
# ls -l tmpfile_symlnk
lrwxrwxrwx 1 root friends 7 2012-05-22 20:03 tmpfile_symlnk -> tmpfile
Change owner only if a file is owned by a particular user
Using chown “–from” flag, you can change the owner of a file,
only if that file is already owned by a particular owner.
# ls -l tmpfile
-rw-r--r-- 1 root friends 0 2012-05-22 20:03 tmpfile
# chown --from=guest himanshu tmpfile# ls -l tmpfile
-rw-r--r-- 1 root friends 0 2012-05-22 20:03 tmpfile
# chown --from=root himanshu tmpfile
# ls -l tmpfile
-rw-r--r-- 1 himanshu friends 0 2012-05-22 20:03 tmpfile
•
•
•
•
In the example above, we verified that the original
owner/group of the file ‘tmpfile’ was root/friends.
Next we used the ‘–from’ flag to change the owner to
‘himanshu’ but only if the existing owner is ‘guest’.
Now, as the existing owner was not ‘guest’. So, the command
failed to change the owner of the file.
Next we tried to change the owner if the existing owner is
‘root’ (which was true) and this time command was
successful and the owner was changed to ‘himanshu’.
Change group only if a file already belongs to a certain group
Here also the flag ‘–from’ is used but in the following way:
# ls -l tmpfile
-rw-r--r-- 1 himanshu friends 0 2012-05-22 20:03 tmpfile
# chown --from=:friends :family tmpfile
# ls -l tmpfile
-rw-r--r-- 1 himanshu family 0 2012-05-22 20:03 tmpfile
Since the file ‘tmpfile’ actually belonged to group ‘friends’ so
the condition was correct and the command was successful.
So we see that by using the flag ‘–from=:<conditional-group-
name>’ we can change the group under a particular condition.
NOTE: By following the template ‘–from=<conditional-owner-
name>:<conditional-group-name>’, condition on both the owner and
group can be applied.
Copy the owner/group settings from one file to another
This is possible by using the ‘–reference’ flag.
# ls -l file
-rwxr-xr-x 1 himanshu family 8968 2012-04-09 07:10 file
# ls -l tmpfile-rw-r--r-- 1 root friends 0 2012-05-22 20:03 tmpfile
# chown --reference=file tmpfile
# ls -l tmpfile
-rw-r--r-- 1 himanshu family 0 2012-05-22 20:03 tmpfile
In the above example, we first checked the owner/group of the
reference-file ‘file’ and then checked the owner/group of the
target-file ‘tmpfile’. Both were different. Then we used the
chown command with the ‘–reference’ option to apply the
owner/group settings from the reference file to the target file.
The command was successful and the owner/group settings of
‘tmpfile’ were made similar to the ‘file’.
Change the owner/group of the files by traveling the directories
recursively
This is made possible by the ‘-R’ option.
chown -R himanshu:family linux/
chmod- change file access permissions or change the file modes
$ ls -lh
-rw-r----- 1 ramesh team-dev 5.0K Jun 13 15:27 mthesaur.txt.gz
Yellow color shows permission for owner/User
Red color shows permission for group
grey color shows permission for others/World
Numeric values for the read, write and execute permissions:
Read
4
Write
2
Execute 1
To have combination of permissions, add required numbers. For
example, for read and write permission, it is 4+2 = 6
Change File and Directory Permissions Using Chmod Command
give read, write ( 4+2 = 6 ) to user and read ( 4 ) to group and
others.
chmod 644 filename
chmod 644 directory_name(permission changing over directory)
chmod -R 644 directory_name(recursive change of permission on
directory)5.
Useful Linux commands – sed, filter, cut, paste, awk
etc
Cut Command in Unix ( Linux) Examples
Cut command in unix (or linux) is used to select sections of
text from each line of files. You can use the cut command to
select fields or columns from a line by specifying a delimiter
or you can select a portion of text by specifying the range or
characters. Basically the cut command slices a line and extracts
the text.
Write a unix/linux cut command to print characters by position?
The cut command can be used to print characters in a line by
specifying the position of the characters. To print the
characters in a line, use the -c option in cut command
cut -c4 file.txt
The above cut command prints the fourth character in each line
of the file. You can print more than one character at a time by
specifying the character positions in a comma separated list as
shown in the below example
cut -c4,6 file.txt
This command prints the fourth and sixth character in each line.
Write a unix/linux cut command to print characters by range?
You can print a range of characters in a line by specifying the
start and end position of the characters.
cut -c4-7 file.txt
The above cut command prints the characters from fourth position
to the seventh position in each line. To print the first six
characters in a line, omit the start position and specify only
the end position.cut -c-6 file.txt
To print the characters from tenth position to the end, specify
only the start position and omit the end position.
cut -c10- file.txt
Write a unix/linux cut command to print the fields using the
delimiter?
You can use
fields in a
can be used
specify the
the cut command just as awk command to extract the
file using a delimiter. The -d option in cut command
to specify the delimiter and -f option is used to
field position.
cut -d ':' -f2 /etc/passwd
This command prints the second field in each line by treating
the space as delimiter. You can print more than one field by
specifying the position of the fields in a comma delimited list.
cut -d ':' -f2,3 /etc/passwd
Write a unix/linux cut command to display range of fields?
You can print a range of fields by specifying the start and end
position.
cut -d':' -f1-3 /etc/passwd
The above command prints the first, second and third fields. To
print the first three fields, you can ignore the start position
and specify only the end position.
cut -d':' -f-3 /etc/passwd
To print the fields from second fields to last field, you can
omit the last field position.
cut -d':' -f2- /etc/passwd
The input file contains the below textcat filenames.txt
logfile.dat
sum.pl
add_int.sh
Using the cut command extract the portion after the dot.
First reverse the text in each line and then apply the command on it.
root@Troy:~# rev filename.txt |cut -d '.' -f1|rev
dat
pl
sh
paste command – Merge file lines
Paste the line1 of file1, file2, .. fileN into the line1 of the
output. It will repeat the same for all lines. Each file’s line
will be delimited by tab.
Paste output:
$ paste f1 f2 f3
f1-line1<tab>f2-line1<tab>f3-line1
f1-line2<tab>f2-line2<tab>f3-line2
f1-line3<tab>f2-line3<tab>f3-line3
...
In the following example, corresponding lines from three
different files are combined and shown appropriately.
root@Troy:~# cat emp-firstname.txt
Emma
Alex
MadisonSanjay
Nisha
root@Troy:~# cat emp-lastname.txt
Thomas
Jason
Randy
Gupta
Singh
root@Troy:~# cat emp-number.txt
100
200
300
400
500
#paste emp-number.txt emp-firstname.txt emp-lastname.txt
100 Emma Thomas
200 Alex Jason
300 Madison Randy
400 Sanjay Gupta
500 Nisha SinghUnix Sed Introduction
• sed is a “non-interactive” stream-oriented editor. Since its
an “non-interactive” it can be used to automate editing if
desired.
• The name sed is an abbreviation for stream editor, and the
utility derives many of its commands from the ed line-editor
(ed was the first UNIX text editor).
• This allows you to edit multiple files, or to perform common
editing operations without ever having to open vi or emacs.
• sed reads from a file or from its standard input, and
outputs to its standard output.
• sed has two buffers which are called pattern buffer and hold
buffer. Both are initially empty.
Unix Sed Working methodology
This is called as one execution cycle. Cycle continues till end
of file/input is reached.
1. Read a entire line from stdin/file.
2. Removes any trailing newline.
3. Places the line, in its pattern buffer.
4. Modify the pattern buffer according to the supplied
commands.
5. Print the pattern buffer to stdout.
Printing Operation in Sed
Linux Sed command allows you to print only specific lines based
on the line number or pattern matches. “p” is a command for
printing the data from the pattern buffer.
To suppress automatic printing of pattern space use -n command
with sed. sed -n option will not print anything, unless an
explicit request to print is found.
Syntax:
# sed -n 'ADDRESS'p filename
# sed -n '/PATTERN/p' filename
Let us first create thegeekstuff.txt file that will be used in
all the examples mentioned below.
# cat thegeekstuff.txt
1. Linux - Sysadmin, Scripting etc.
2. Databases - Oracle, mySQL etc.
3. Hardware4. Security (Firewall, Network, Online Security etc)
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time
available)
8. Website Design
9. Software Development
10.Windows- Sysadmin, reboot etc.
5 Sed ADDRESS Format Examples
Sed Address Format 1: NUMBER
This will match only Nth line in the input.
# sed -n ‘N’p filename
For example, 3p prints third line of input file thegeekstuff.txt
as shown below.
# sed -n '3'p thegeekstuff.txt
3. Hardware
Sed Address Format 2: NUMBER1~NUMBER2
M~N with “p” command prints every Nth line starting from line M.
# sed -n ‘M~N’p filename
For example, 3~2p prints every 2nd line starting from 3rd line
as shown below.
# sed -n '3~2'p thegeekstuff.txt
3. Hardware
5. Storage
7. Productivity (Too many technologies to explore, not much time
available)
9. Software Development
Sed Address Format 3: START,END
M,N with “p” command prints Mth line to Nth line.
# sed -n ‘M,N’p filename
For example, 4,8p prints from 4th line to 8th line from input
file thegeekstuff.txt# sed -n '4,8'p thegeekstuff.txt
4. Security (Firewall, Network, Online Security etc)
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time
available)
8. Website Design
Sed Address Format 4: ‘$’ Last Line
$ with “p” command matches only the last line from the input.
# sed -n ‘$’p filename
For example, $p prints only the last line as shown below.
# sed -n '$'p thegeekstuff.txt
10.Windows- Sysadmin, reboot etc.
Sed Address Format 5: NUMBER,$
N,$ with “p” command prints from Nth line to end of file.
# sed -n ‘N,$’p filename
For example 4,$p prints from 4th line to end of file.
# sed -n '4,$'p thegeekstuff.txt
4. Security (Firewall, Network, Online Security etc)
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time
available)
8. Website Design
9. Software Development
10.Windows- Sysadmin, reboot etc.
Sed Pattern Format 1: PATTERN
PATTERN could be unix regular expression. The below command
prints only the line which matches the given pattern.
# sed -n /PATTERN/p filename
For example, following prints the line only which matches the
pattern “Sysadmin”.# sed -n /Sysadmin/p thegeekstuff.txt
1. Linux - Sysadmin, Scripting etc.
10.Windows- Sysadmin, reboot etc.
Sed Pattern Format 3: ADDRESS,/PATTERN/
It prints from the Nth line of the input, to the line which
matches the pattern. If the pattern doesnt match, it prints upto
end of the input.
# sed -n ‘N,/PATTERN/’p filename
For example, 4th line matches the pattern “Security”, so it
prints from 3rd line to 4th line.
# sed -n '3,/Security/'p thegeekstuff.txt
3. Hardware
4. Security (Firewall, Network, Online Security etc)
Sed Pattern Format 4: /PATTERN/,$
It prints from the line matches the given pattern to end of file.
# sed -n ‘/PATTERN/,$’p filename
# sed -n '/Website/,$'p thegeekstuff.txt
8. Website Design
9. Software Development
10.Windows- Sysadmin, reboot etc.
Sed Pattern Format 5: /PATTERN/,+N
It prints the lines which matches the pattern and next N lines
following the matched line.
# sed -n ‘/PATTERN/,+N’p filename
For example, following prints the 5th line which matches the
pattern /Storage/ and next two lines following /Storage/.
# sed -n '/Storage/,+2'p thegeekstuff.txt
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time
available)
Sed Pattern Format 6: /PATTERN/,/PATTERN/
Prints the section of file between two regular expression
(including the matched line ).
# sed -n ‘/P1/,/P2/’p filenameFor example, 5th line matches “Storage” and 8th line matches
“Design”, so it prints 5th to 8th.
# sed -n '/Storage/,/Design/'p thegeekstuff.txt
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time
available)
8. Website Design
in this article, let us review how to delete lines from a file
using address and patterns with 8 awesome examples.
• “p” command prints the buffer (remember to use -n option
with “p”)
• “d” command is just opposite, its for deletion. ‘d’ will
delete the pattern space buffer and immediately starts the
next cycle.
Syntax:
# sed 'ADDRESS'd filename
# sed /PATTERN/d filename
Syntax for ADDRESSES and PATTERNS given in the printing is
applicable for deletion also, except -n option. (-n only to
suppress printing pattern buffer, can be used with “p” command )
Let us first creates thegeekstuff.txt file that will be used in
all the examples mentioned below.
# cat thegeekstuff.txt
1. Linux - Sysadmin, Scripting etc.
2. Databases - Oracle, mySQL etc.
3. Hardware
4. Security (Firewall, Network, Online Security etc)
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time
available)
8. Website Design
9. Software Development
10.Windows- Sysadmin, reboot etc.
1. Delete Nth Line‘Nd’ deletes the Nth line and prints the other lines.
sed ‘Nd’ filename
As per sed methodology,
• It reads the first line and places in its pattern buffer.
• Check whether supplied command is true for this line, if
true, deletes pattern space buffer and starts next cycle.
i.e Read next line.
• If supplied command doesnt true, as its normal behaviour it
prints the content of the pattern space buffer.
For example, 3d deletes 3rd line and prints other lines as shown
below.
$ sed 3d thegeekstuff.txt
1. Linux - Sysadmin, Scripting etc.
2. Databases - Oracle, mySQL etc.
4. Security (Firewall, Network, Online Security etc)
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time
available)
8. Website Design
9. Software Development
10.Windows- Sysadmin, reboot etc.
2. Delete Starting from 3rd line and every 2nd line from there.
$ sed '3~2d' thegeekstuff.txt
1. Linux - Sysadmin, Scripting etc.
2. Databases - Oracle, mySQL etc.
4. Security (Firewall, Network, Online Security etc)
6. Cool gadgets and websites
8. Website Design
10.Windows- Sysadmin, reboot etc.
3. Delete from 4th to 8th line from file.
$ sed '4,8d' thegeekstuff.txt
1. Linux - Sysadmin, Scripting etc.
2. Databases - Oracle, mySQL etc.
3. Hardware
9. Software Development
10.Windows- Sysadmin, reboot etc.
4. Delete the last line from input.$ sed '$d' thegeekstuff.txt
1. Linux - Sysadmin, Scripting etc.
2. Databases - Oracle, mySQL etc.
3. Hardware
4. Security (Firewall, Network, Online Security etc)
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time
available)
8. Website Design
9. Software Development
5. Delete the line which matches the given pattern from input.
For example, the below command deletes the line which matches
with “Sysadmin”.
$ sed /Sysadmin/d thegeekstuff.txt
2. Databases - Oracle, mySQL etc.
3. Hardware
4. Security (Firewall, Network, Online Security etc)
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time
available)
8. Website Design
9. Software Development
6. Deletes the line from which matches the given pattern to end
of the file.
$ sed '/Website/,$d' thegeekstuff.txt
1. Linux - Sysadmin, Scripting etc.
2. Databases - Oracle, mySQL etc.
3. Hardware
4. Security (Firewall, Network, Online Security etc)
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time
available)
7. Deletes the line from which matches the given pattern and
2lines next to that.
$ sed '/Storage/,+2d' thegeekstuff.txt
1. Linux - Sysadmin, Scripting etc.2. Databases - Oracle, mySQL etc.
3. Hardware
4. Security (Firewall, Network, Online Security etc)
8. Website Design
9. Software Development
10.Windows- Sysadmin, reboot etc.
8. Delete blank Line from a file using sed
You can also remove blank lines with sed. The following sed
example shows how to use sed and remove blank lines.
$ sed '/^$/d' thegeekstuff.txt
1. Linux - Sysadmin, Scripting etc.
2. Databases - Oracle, mySQL etc.
3. Hardware
4. Security (Firewall, Network, Online Security etc)
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time
available)
8. Website Design
9. Software Development
10.Windows- Sysadmin, reboot etc.
In this article let us review how to use sed substitute command
“s”.
The `s’ command is probably the most important in `sed’ and has
a lot of different options.
The `s’ command attempts to match the pattern space against the
supplied REGEXP; if the match is successful, then that portion
of the pattern space which was matched is replaced with
REPLACEMENT.
Syntax:
#sed 'ADDRESSs/REGEXP/REPLACEMENT/FLAGS' filename
#sed 'PATTERNs/REGEXP/REPLACEMENT/FLAGS' filename
•
•
•
•
s is substitute command
/ is a delimiter
REGEXP is regular expression to match
REPLACEMENT is a value to replace
FLAGS can be any of the following• g Replace all the instance of REGEXP with REPLACEMENT
• n Could be any number,replace nth instance of the REGEXP
with REPLACEMENT.
• p If substitution was made, then prints the new pattern
space.
• i match REGEXP in a case-insensitive manner.
• w file If substitution was made, write out the result to the
given file.
• We can use different delimiters ( one of @ % ; : ) instead
of /
Let us first create thegeekstuff.txt file that will be used in
all the examples mentioned below.
$ cat thegeekstuff.txt
# Instruction Guides
1. Linux Sysadmin, Linux Scripting etc.
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)
# Additional FAQS
6. Windows- Sysadmin, reboot etc.
Let us review some interesting examples for substitution now.
1. Substitute Word “Linux” to “Linux-Unix” Using sed s//
In the example below, in the output line “1. Linux-Unix
Sysadmin, Linux Scripting etc” only first Linux is replaced by
Linux-Unix. If no flags are specified the first match of line is
replaced.
$ sed 's/Linux/Linux-Unix/' thegeekstuff.txt
# Instruction Guides
1. Linux-Unix Sysadmin, Linux Scripting etc.
2. Databases - Oracle, mySQL etc.
3. Security (Firewall, Network, Online Security etc)
4. Storage in Linux-Unix
5. Productivity (Too many technologies to explore, not much time
available)
# Additional FAQS
6. Windows- Sysadmin, reboot etc.
2. Substitute all Appearances of a Word Using sed s//gThe below sed command replaces all occurrences of Linux to
Linux-Unix using global substitution flag “g”.
$ sed 's/Linux/Linux-Unix/g' thegeekstuff.txt
# Instruction Guides
1. Linux-Unix Sysadmin, Linux-Unix Scripting etc.
2. Databases - Oracle, mySQL etc.
3. Security (Firewall, Network, Online Security etc)
4. Storage in Linux-Unix
5. Productivity (Too many technologies to explore, not much time
available)
# Additional FAQS
6. Windows- Sysadmin, reboot etc.
3. Substitute Only 2nd Occurrence of a Word Using sed s//2
In the example below, in the output line “1. Linux Sysadmin,
Linux-Unix Scripting etc.” only 2nd occurance of Linux is
replaced by Linux-Unix.
$ sed 's/Linux/Linux-Unix/2' thegeekstuff.txt
# Instruction Guides
1. Linux Sysadmin, Linux-Unix Scripting etc.
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)
# Additional FAQS
6. Windows- Sysadmin, reboot etc.
4. Write Changes to a File and Print the Changes Using sed s//gpw
The example below has substitution with three flags. It
substitutes all the occurance of Linux to Linux-Unix and prints
the substituted output as well as written the same to the given
the file.
$ sed -n 's/Linux/Linux-Unix/gpw output' thegeekstuff.txt
1. Linux-Unix Sysadmin, Linux-Unix Scripting etc.
4. Storage in Linux-Unix
$ cat output
1. Linux-Unix Sysadmin, Linux-Unix Scripting etc.
4. Storage in Linux-UnixSubstitute Only When the Line Matches with the Pattern Using sed
In this example, if the line matches with the pattern “-”, then
it replaces all the characters from “-” with the empty.
$ sed '/\-/s/\-.*//g' thegeekstuff.txt
# Instruction Guides
1. Linux Sysadmin, Linux Scripting etc.
2. Databases
3. Security (Firewall, Network, Online Security etc)
4. Storage in Linux
5. Productivity (Too many technologies to explore, not much time
available)
# Additional FAQS
6. Windows
Delete Last X Number of Characters From Each Line Using sed
This sed example deletes last 3 characters from each line.
$ sed 's/...$//' thegeekstuff.txt
Eliminate Comments Using sed
Delete all the comment lines from a file as shown below using
sed command.
root@Troy:~# sed 's/#//g' test
Instruction Guides
1. Linux Sysadmin, Linux Scripting etc.
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)Additional FAQS
6. Windows- Sysadmin, reboot etc.
root@Troy:~# sed 's/#.*//g' test
1. Linux Sysadmin, Linux Scripting etc.
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)
6. Windows- Sysadmin, reboot etc.
Eliminate Comments and Empty Lines Using sed
In this example, there are two commands seperated by ‘;’
• First command replaces the lines starting with the # to the
blank lines
• Second command deletes the empty lines.
$ sed -e 's/#.*//;/^$/d' thegeekstuff.txt
1. Linux Sysadmin, Linux Scripting etc.
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)
6. Windows- Sysadmin, reboot etc.
Convert DOS newlines (CR/LF) to Unix format Using sed
Copy the DOS file to Unix, you could find \r\n in the end of
each line.This example converts the DOS file format to Unix file
format using sed command.
$sed 's/.$//' filenameSED:Append, Insert, Replace, and Count File Lines
Append Lines Using Sed Command
Sed provides the command “a” which appends a line after every line with the address
or pattern.
Syntax:
#sed 'ADDRESS a\Line which you want to append' filename
#sed '/PATTERN/ a\Line which you want to append' filename
Insert Lines Using Sed Command
Sed command “i” is used to insert a line before every line with the range or
pattern.
Syntax:
#sed 'ADDRESS i\Line which you want to insert' filename
#sed '/PATTERN/ i\Line which you want to insert' filename
Replace Lines Using Sed Command
“c” command in sed used to replace every line matches with the pattern or
ranges with the new given line.
Syntax:
#sed 'ADDRESS c\new line' filename
#sed '/PATTERN/ c\new line' filename
root@Troy:~# cat test
1. Instruction Guides
2. Linux Sysadmin, Linux Scripting etc.
3. Databases - Oracle, mySQL etc.
4. Security (Firewall, Network, Online Security etc)
5. Storage in Linux
6. Productivity (Too many technologies to explore, not much time available)
7 Additional FAQS
8. Windows- Sysadmin, reboot etc.root@Troy:~# sed '3 a\Cool gadgets and websites' test
1. Instruction Guides
2. Linux Sysadmin, Linux Scripting etc.
3. Databases - Oracle, mySQL etc.
Cool gadgets and websites
4. Security (Firewall, Network, Online Security etc)
5. Storage in Linux
6. Productivity (Too many technologies to explore, not much time available)
7 Additional FAQS
8. Windows- Sysadmin, reboot etc.
root@Troy:~# sed '3 i\Cool gadgets and websites' test
1. Instruction Guides
2. Linux Sysadmin, Linux Scripting etc.
Cool gadgets and websites
3. Databases - Oracle, mySQL etc.
4. Security (Firewall, Network, Online Security etc)
5. Storage in Linux
6. Productivity (Too many technologies to explore, not much time available)
7 Additional FAQS
8. Windows- Sysadmin, reboot etc.
root@Troy:~# sed '3 c\Cool gadgets and websites' test
1. Instruction Guides
2. Linux Sysadmin, Linux Scripting etc.
Cool gadgets and websites
4. Security (Firewall, Network, Online Security etc)
5. Storage in Linux
6. Productivity (Too many technologies to explore, not much time available)
7 Additional FAQS
8. Windows- Sysadmin, reboot etc.
root@Troy:~# sed '/Sysadmin/ a\Linux Scripting/' test
1. Instruction Guides
2. Linux Sysadmin, Linux Scripting etc.
Linux Scripting/
3. Databases - Oracle, mySQL etc.
4. Security (Firewall, Network, Online Security etc)
5. Storage in Linux
6. Productivity (Too many technologies to explore, not much time available)
7 Additional FAQS
8. Windows- Sysadmin, reboot etc.
Linux Scripting/
root@Troy:~# sed '/Sysadmin/ i\Linux Scripting/' test
1. Instruction Guides
Linux Scripting/
2. Linux Sysadmin, Linux Scripting etc.3. Databases - Oracle, mySQL etc.
4. Security (Firewall, Network, Online Security etc)
5. Storage in Linux
6. Productivity (Too many technologies to explore, not much time available)
7 Additional FAQS
Linux Scripting/
8. Windows- Sysadmin, reboot etc.
root@Troy:~# sed '/Sysadmin/ c\Linux Scripting/' test
1. Instruction Guides
Linux Scripting/
3. Databases - Oracle, mySQL etc.
4. Security (Firewall, Network, Online Security etc)
5. Storage in Linux
6. Productivity (Too many technologies to explore, not much time available)
7 Additional FAQS
Linux Scripting/
Print Line Numbers Using Sed Command
“=” is a command in sed to print the current line number to the standard
output.
Syntax:
#sed '=' filename
The above send command syntax prints line number in the first line and the
original line from the file in the next line .
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
Find the line number which contains the pattern
The below sed command prints the line number for which matches with the
pattern “Databases”
root@Troy:~# sed -n '/Storage/=' test1
4Print the total number of lines in a file
Line number of the last line of the file will be the total lines in a file.
Pattern $ specifies the last line of the file.
root@Troy:~# sed -n '$=' test1
6
Printing Range of line numbers
Print the line numbers for the lines matches from the pattern “Oracle” to
“Productivity”.
root@Troy:~# sed -n '/Oracle/,/Productivity/{
=
p
}' test1
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)Awk Introduction and Printing Operations
Awk is a programming language which allows easy manipulation of
structured data and the generation of formatted reports. Awk
stands for the names of its authors “Aho, Weinberger, and
Kernighan”
The Awk is mostly used for pattern scanning and processing. It
searches one or more files to see if they contain lines that
matches with the specified patterns and then perform associated
actions.
Some of the key features of Awk are:
• Awk views a text file as records and fields.
• Like common programming language, Awk has variables,
conditionals and loops
• Awk has arithmetic and string operators.
• Awk can generate formatted reports
Awk reads from a file or from its standard input, and outputs to
its standard output. Awk does not get along with non-text files.
Syntax:
awk '/search pattern1/ {Actions}
/search pattern2/ {Actions}' file
In the above awk syntax:
•
•
•
•
•
search pattern is a regular expression.
Actions – statement(s) to be performed.
several patterns and actions are possible in Awk.
file – Input file.
Single quotes around program is to avoid shell not to
interpret any of its special characters.
Awk Working Methodology
1. Awk reads the input files one line at a time.
2. For each line, it matches with given pattern in the given
order, if matches performs the corresponding action.
3. If no pattern matches, no action will be performed.
4. In the above syntax, either search pattern or action are
optional, But not both.
5. If the search pattern is not given, then Awk performs the
given actions for each line of the input.
6. If the action is not given, print all that lines that
matches with the given patterns which is the default action.
7. Empty braces with out any action does nothing. It wontperform default printing operation.
8. Each statement in Actions should be delimited by semicolon.
Let us create employee.txt file which has the following content,
which will be used in the
examples mentioned below.
$cat
100
200
300
400
500
employee.txt
Thomas Manager
Jason
Developer
Sanjay Sysadmin
Nisha
Manager
Randy
DBA
Sales
Technology
Technology
Marketing
Technology
$5,000
$5,500
$7,000
$9,500
$6,000
Awk Example 1. Default behavior of Awk
By default Awk prints every line from the file.
$ awk '{print;}' employee.txt
100 Thomas Manager
Sales
200 Jason
Developer Technology
300 Sanjay Sysadmin
Technology
400 Nisha
Manager
Marketing
500 Randy
DBA
Technology
$5,000
$5,500
$7,000
$9,500
$6,000
In the above example pattern is not given. So the actions are
applicable to all the lines.
Action print with out any argument prints the whole line by
default. So it prints all the lines of the file with out fail.
Actions has to be enclosed with in the braces.
Awk Example 2. Print the lines which matches with the pattern.
$ awk '/Thomas|Nisha/' employee.txt
100 Thomas Manager
Sales
$5,000
400 Nisha
Manager
Marketing
$9,500
In the above example it prints all the line which matches with
the ‘Thomas’ or ‘Nisha’. It has two patterns. Awk accepts any
number of patterns, but each set (patterns and its corresponding
actions) has to be separated by newline.
Awk Example 3. Print only specific field.
Awk has number of built in variables. For each record i.e line,
it splits the record delimited by whitespace character by
default and stores it in the $n variables. If the line has 4
words, it will be stored in $1, $2, $3 and $4. $0 represents
whole line. NF is a built in variable which represents total
number of fields in a record.$ awk '{print $2,$5;}' employee.txt
Thomas
$5,000
Jason
$5,500
Sanjay
$7,000
Nisha
$9,500
Randy
$6,000
$ awk '{print $2,$NF;}' employee.txt
Thomas
$5,000
Jason
$5,500
Sanjay
$7,000
Nisha
$9,500
Randy
$6,000
In the above example $2 and $5 represents Name and Salary
respectively. We can get the Salary using $NF also, where $NF
represents last field. In the print statement ‘,’ is a
concatenator.
Awk Example 4. Initialization and Final Action
Awk has two important patterns which are specified by the
keyword called BEGIN and END.
Syntax:
BEGIN { Actions}
{ACTION} # Action for every line in a file
END { Actions }
# is for comments in Awk
Actions specified in the BEGIN section will be executed before
starts reading the lines from the input.
END actions will be performed after completing the reading and
processing the lines from the input.
$ awk 'BEGIN {print "Name\tDesignation\tDepartment\tSalary";}
> {print $2,"\t",$3,"\t",$4,"\t",$NF;}
> END{print "Report Generated\n--------------";
> }' employee.txt
Name
Designation
Department
Salary
Thomas
Manager
Sales
$5,000
Jason
Developer
Technology
$5,500
Sanjay
Sysadmin
Technology
$7,000
Nisha
Manager
Marketing
$9,500
Randy
DBA
Technology
$6,000Report Generated
--------------
In the above example, it prints headline and last file for the
reports.
Awk Example 5. Find the employees who has employee id greater
than 200
$ awk '$1 >200' employee.txt
300 Sanjay Sysadmin
Technology $7,000
400 Nisha
Manager
Marketing
$9,500
500 Randy
DBA
Technology $6,000
In the above example, first field ($1) is employee id. So if $1
is greater than 200, then just do the default print action to
print the whole line.
Awk Example 6. Print the list of employees in Technology
department
Now department name is available as a fourth field, so need to
check if $4 matches with the string “Technology”, if yes print
the line.
$ awk '$4 ~/Technology/' employee.txt
200 Jason
Developer Technology $5,500
300 Sanjay Sysadmin
Technology $7,000
500 Randy
DBA
Technology $6,000
Operator ~ is for comparing with the regular expressions. If it
matches the default action i.e print whole line will be
performed.
Awk Example 7. Print number of employees in Technology department
The below example, checks if the department is Technology, if it
is yes, in the Action, just increment the count variable, which
was initialized with zero in the BEGIN section.
$ awk 'BEGIN { count=0;}
$4 ~ /Technology/ { count++; }
END { print "Number of employees in Technology Dept =",count;}'
employee.txt
Number of employees in Technology Dept = 3
Then at the end of the process, just print the value of count
which gives you the number of employees in Technology department.Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR
Awk has several powerful built-in variables.
There are two types of built-in variables in Awk.
1. Variable which defines values which can be changed such as
field separator and record separator.
2. Variable which can be used for processing and reports such
as Number of records, number of fields.
1. Awk FS Example: Input field separator variable.
Awk reads and parses each line from input based on whitespace
character by default and set the variables $1,$2 and etc. Awk FS
variable is used to set the field separator for each record. Awk
FS can be set to any single character or regular expression. You
can use input field separator using one of the following two
options:
1. Using -F command line option.
2. Awk FS can be set like normal variable.
Syntax:
$ awk -F 'FS' 'commands' input_filename
awk -F ':' '{print $1}' /etc/passwd
(or)
$ awk 'BEGIN{FS="FS";}'
awk 'BEGIN{FS=":"}{print $1}' /etc/passwd
Awk FS is any single character or regular expression which you
want to use as a input field separator.
• Awk FS can be changed any number of times, it retains its
values until it is explicitly changed. If you want to change
the field separator, its better to change before you read
the line. So that change affects the line what you read.
Here is an awk FS example to read the /etc/passwd file which has
“:” as field delimiter.$ cat etc_passwd.awk
BEGIN{
FS=":"
print "Name\tUserID\tGroupID\tHomeDirectory";
}
{
print $1"\t"$3"\t"$4"\t"$6;
}
END{
print NR,"Records Processed";
}
or
root@Troy:~# cat etc_passwd.awk
BEGIN{
FS=":"
OFS="\t"
print "Name\tUserID\tGroupID\tHomeDirectory";
}
{
print $1,$3,$4,$6;
}
END{print "--------------------------------------------------------"
print NR,"Records Processed";
}
$awk -f etc_passwd.awk /etc/passwd
2. Awk OFS Example: Output Field Separator Variable
Awk OFS is an output equivalent of awk FS variable. By default
awk OFS is a single space character. Following is an awk OFS
example.
$ awk -F':' '{print $3,$4;}' /etc/passwd
41 41
100 101
101 102
103 7
105 111
110 116
111 117
112 119
Concatenator in the print statement “,” concatenates two
parameters with a space which is the value of awk OFS by
default. So, Awk OFS value will be inserted between fields in
the output as shown below.
awk -F ":" 'BEGIN{OFS="="}{print $3,$4}' /etc/passwd
41=41
100=101
101=102
103=7
105=111
110=116
111=117
112=119
3. Awk RS Example: Record Separator variable
Awk RS defines a line. Awk reads line by line by default.Let us take students marks are stored in a file, each records
are separated by double new line, and each fields are separated
by a new line character.
$cat student.txt
Jones
2143
78
84
77
Gondrol
2321
56
58
45
RinRao
2122
38
37
65
Edwin
2537
78
67
45
Dayan
2415
30
47
20
Now the below Awk script prints the Student name and Roll no
from the above input file.
root@ubuntu:~# awk -f student.awk student
Jones 2143
Gondrol 2321RinRao 2122
Edwin 2537
Dayan 2415
root@ubuntu:~# cat student.awk
BEGIN{
RS="\n\n"
FS="\n"
OFS="\t"
}
{
print $1,$2;
}
In the script student.awk, it reads each student detail as a
single record,because awk RS has been assigned to double newline character and each line in a record is a field, since FS is
newline character.
4. Awk ORS Example: Output Record Separator Variable
Awk ORS is an Output equivalent of RS. Each record in the output
will be printed with this delimiter. Following is an awk ORS
example:
root@Troy:~# cat student.awk
BEGIN{
RS="\n\n"
FS="\n"
OFS="\t"
ORS=";"
}
{
print $1,$2
}root@Troy:~# awk -f student.awk student.txt
Jones 2143;Gondrol
2321;RinRao
2122;Edwin 2537;Dayan 2415;
In the above script,each records in the file student-marks file
is delimited by the character ;
5. Awk NR Example: Number of Records Variable
Awk NR gives you the total number of records being processed or
line number. In the following awk NR example, NR variable has
line number, in the END section awk NR tells you the total
number of records in a file.
6. Awk NF Example: Number of Fields in a record
Awk NF gives you the total number of fields in a record. Awk NF
will be very useful for validating whether all the fields are
exist in a record.
cat student-marks
Jones 2143 78 84 77
Gondrol 2321 56 58 45
RinRao 2122 38 37
Edwin 2537 78 67 45
Dayan 2415 30 47
The following Awk script, prints Record(line) number, and number
of fields in that record. So It will be very simple to find out
that Test3 score is missing.
root@Troy:~# awk '{print "Processing Record:",NR "has number of
field-"NF }END{print NR,"Total Number of Records are processed"}'
student-marks.txt
Processing Record: 1has number of field-5
Processing Record: 2has number of field-5Processing Record: 3has number of field-4
Processing Record: 4has number of field-5
Processing Record: 5has number of field-4
5 Total Number of Records are processed
8. Awk FNR Example: Number of Records relative to the current
input file
When awk reads from the multiple input file, awk NR variable
will give the total number of records relative to all the input
file. Awk FNR will give you number of records for each input
file.
$ awk '{print
student-marks
student-marks
student-marks
student-marks
student-marks
bookdetails 1
bookdetails 2
bookdetails 3
bookdetails 4
bookdetails 5
FILENAME, FNR;}' student-marks bookdetails
1
2
3
4
5
In the above example, instead of awk FNR, if you use awk NR, for
the file bookdetails the you will get from 6 to 10 for each
record.
Powerful Awk Operators Examples (Unary, Binary, Arithmetic,
String, Assignment, Conditional, Reg-Ex Awk Operators)
There are two types of operators in Awk.
1. Unary Operator – Operator which accepts single operand is
called unary operator.
2. Binary Operator – Operator which accepts more than one
operand is called binary operator.Awk Unary Operator
Operator
Description
+ Positivate the number
- Negate the number
++ Auto Increment
-- Auto Decrement
Awk Binary Operator
There are different kinds of binary operators are available in
Awk. It is been classified based on its usage.
Awk Arithmetic Opertors
The following operators are used for performing arithmetic
calculations.
Operator
Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division
Awk String Operator
For string concatenation Awk has the following operators.
Operator Description
(space) String Concatenation
Awk Assignment Operators
Awk has Assignment operator and Shortcut assignment operator as
listed below.
Operator
DescriptionAwk Conditional Operators
Awk has the following list of conditional operators which can be
used with control structures and looping statement which will be
covered in the coming article
Operator Description
> Is greater than
>= Is greater than or equal to
< Is less than
<= Is less than or equal to
== Is equal to
!= Is not equal to
&& Both the conditional expression should be true
|| Any one of the conditional expression should be true
Awk Regular Expression Operator
Operator Description
~ Match operator
!~ No Match operator
Awk Operator Examples
Now let us review some examples that uses awk operators. Let us
use /etc/passwd as input file in these examples.
Awk Example 1: Count the total number of fields in a file.
The below awk script, matches all the lines and keeps adding the
number of fields in each line,using shortcut addition assignment
operator. The number of fields seen so far is kept in a variable
named ‘total’. Once the input has been processed, special
pattern ‘END {...}’ is executed, which prints the total number of
fields.
awk -F ':' '{ total += NF }; END { print total }' /etc/passwdAwk Example 2: Count number of users who is using /bin/sh shell
In the below awk script, it matches last field of all lines
containing the pattern /bin/sh. Regular expression should be
closed between //. So all the front slash(/) has to be escaped
in the regular expression. When a line matches variable ‘Total’
gets incremented by one. Printed the value of the ‘Total’ in the
END section.
awk -F ':' '$NF ~ /\/bin\/sh/ { n++ }; END { print n }'
/etc/passwd
Awk Example 3: Find the user details who is having the highest
USER ID
The below awk script, keeps track of the largest number in the
field in variable ‘maxuid’ and the corresponding line will be
stored in variable ‘maxline’. Once it has looped over all lines,
it prints them out.
awk -F ':' '$3 > maxuid { maxuid=$3; maxline=$0 }; END { print
maxuid, maxline }' /etc/passwd
65534 nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
or
sort -t : -n
-k 3,3n /etc/passwd|tail -n1
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
Awk Example 4: Print the even-numbered lines
The below awk script, processes each line and checks NR % 2 ==0
i.e if NR is multiple of 2. It performs the default operation
which printing the whole line.
awk 'NR % 2 == 0' /etc/passwd
Awk Example 5.Print every line which has the same USER ID and
GROUP ID
The below awk script prints the line only if $3(USER ID) an
$4(GROUP ID) are equal. It checks this condition for each line
of input, if it matches, prints the whole line.
awk -F':' '$3==$4' /etc/passwdAwk Example 6: Print user details who has USER ID greater than
or equal to 100 and who has to use /bin/sh
In the below Awk statement, there are two conditional expression
one is User id($3) greater than or equal to 100, and second is
last field should match with the /bin/sh , ‘&&’ is to print only
if both the above conditions are true.
awk -F':' '$3>=100 && $NF ~ /\/bin\/sh/' /etc/passwd
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
speech-dispatcher:x:106:29:Speech Dispatcher,,,:/var/run/speech-
dispatcher:/bin/sh
Awk Example 7: Print user details who doesn’t have the comments
in /etc/passwd file
The below Awk script, reads each line and checks for fifth field
is empty, if it is empty, it prints the line.
$awk -F ':' '$5 == "" ' passwd.txt
Memory Usage – free, top etc. ; Text editor (vi editor – with all commands)
and processing with examples
Free
Free command displays information about the physical (RAM) and swap memory of
your system.
In the example below, the total physical memory on this system is 1GB. The
values displayed below are in KB.
# free
total
used
Mem: 1034624
1006696
-/+ buffers/cache:
Swap:
2031608
free
shared buffers
27928 0
174136
216668
817956
0
2031608
cached
615892
The following example will display the total memory on your system including
RAM and Swap.
In the following command:
• option m displays the values in MB
• option t displays the “Total” line, which is sum of physical and swapmemory values
• option o is to hide the buffers/cache line from the above example.
# free -mto
total
1010
1983
2994
Mem:
Swap:
Total:
used
983
0
983
free
27
1983
2011
shared
0
buffers
170
cached
601
TOP
Top command displays all the running process in the system ordered by certain
columns. This displays the information real-time.
You can kill a process without exiting from top. Once you’ve located a
process that needs to be killed, press “k” which will ask for the process id,
and signal to send. If you have the privilege to kill that particular PID, it
will get killed successfully.
PID to kill: 1309
Kill PID 1309 with signal [15]:
PID USER
PR NI VIRT RES
1309 geek
23
0 2483m 1.7g
1882 geek
25
0 2485m 1.7g
5136 root
16
0 38040 14m
SHR
27m
26m
9836
S %CPU %MEM
S
0
21.8
S
0
21.7
S
0
0.2
TIME+
COMMAND
45:31.32 gagent
22:38.97 gagent
0:00.39
nautilus
Use top -u to display a specific user processes only in the top command output.
$ top -u geek
While unix top command is running, press u which will ask for
username as shown below.
Which
PID
1309
1882
user (blank for all): geek
USER
PR NI VIRT RES SHR S %CPU %MEM
TIME+ COMMAND
geek
23
0 2483m 1.7g 27m S
0 21.8 45:31.32 gagent
geek
25
0 2485m 1.7g 26m S
0 21.7 22:38.97 gagent
Type Capital O for sorting the fields
Vmstat
vmstat reports virtual memory statistics. The following are some of vmstat
command examples.vmstat by default will display the memory usage (including
swap) as shown below.
$ vmstat
procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------
r b
swpd
free
buff cache
si
so
bi
bo
in
cs us sy id wa st
0 0 305416 260688 29160 2356920 2
2
4
1
0
0 6 1 92 2 0To execute vmstat every 2 seconds for 10 times, do the following. After executing 10
times, it will stop automatically.
$ vmstat 2 10
procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu-----
r b
swpd
free
buff cache
si
so
bi
bo
in
cs us sy id wa st
1 0
0 537144 182736 6789320
0
0
0
0
1
1 0 0 100 0 0
0 0
0 537004 182736 6789320
0
0
0
0
50
32 0 0 100 0 0
..Vi editor
Modes
Vi has two modes insertion mode and command mode. The editor begins in
command mode, where the cursor movement and text deletion and pasting occur.
Insertion mode begins upon entering an insertion or change command. [ESC]
returns the editor to command mode (where you can quit, for example by typing
:q!). Most commands execute as soon as you type them except for "colon"
commands which execute when you press the return key.
Quitting
:x Exit, saving changes
:q Exit as long as there have been no changes
ZZ Exit and save changes if any have been made
:
q! Exit and ignore any changes
Inserting Text
i Insert before cursor
I Insert before line
a Append after cursor
A Append after line
o Open a new line after current line
O Open a new line before current line
r Replace one character
R Replace many charactersMotion
h Move left
j Move down
k Move up
l Move right
Arrow Keys These do work, but they may be too slow on big files. Also may
have unpredictable results when arrow keys are not mapped
correctly in client.
w Move to next word
W Move to next blank delimited word
b Move to the beginning of the word
B Move to the beginning of blank delimited word
^ Moves to the first non-blank character in the current line
+ or Moves to the first character in the next line
- Moves to the first non-blank character in the previous line
e Move to the end of the word
E Move to the end of Blank delimited word
( Move a sentence back
) Move a sentence forward
{ Move a paragraph back
} Move a paragraph forward
[[ Move a section back
]] Move a section forward
0 or | Move to the begining of the line
n| Moves to the column n in the current line
$ Move to the end of the line1G Move to the first line of the file
G Move to the last line of the file
nG Move to nth line of the file
:n Move to nth line of the file
fc Move forward to c
Fc Move back to c
H Move to top of screen
nH Moves to nth line from the top of the screen
M Move to middle of screen
L Move to botton of screen
nL Moves to nth line from the bottom of the screen
Control-d Move forward 1⁄2 screen
Control-f Move forward one full screen
Control-u Move backward 1⁄2 screen
Control-b Move backward one full screen
CTRL-e Moves screen up one line
CTRL-y Moves screen down one line
CTRL-u Moves screen up 1⁄2 page
CTRL-d Moves screen down 1⁄2 page
CTRL-b Moves screen up one page
CTRL-f Moves screen down one page
CTRL-I Redraws screen
z z-carriage return makes the current line the top line on the
page
nz Makes the line n the top line on the pagez. Makes the current line the middle line on the page
nz. Makes the line n the middle line on the page
z- Makes the current line the bottom line on the page
nz- Makes the line n the bottom line on the page
% Move to associated ( ), { }, [ ]
Deleting Text
Almost all deletion commands are performed by typing d followed by a
motion. For example, dw deletes a word. A few other deletes are:
x Delete character to the right of cursor
X Delete character to the left of cursor
D Delete to the end of the line
dd Delete current line
:d Delete current line
:g/^$/d `:g` will execute a command on lines which match a regex. The
regex is 'blank line' and the command is `:d` (delete)
Yanking Text
Like deletion, almost all yank commands are performed by typing y
followed by a motion. For example, y$ yanks to the end of the line.
Two other yank commands are:
yy Yank the current line
:y Yank the current linep Putting text
Put after the position or after the line
P Put before the position or before the line
Search for strings
/string Search forward for string
?string Search back for string
n Search for next instance of string
N Search for previous instance of string
Replace
The search and replace function is accomplished with the :s command.
It is commonly used in combination with ranges or the :g command
(below).
:
%s/pattern/string/flags
Replace pattern with string according to
flags.
g Flag - Replace all occurences of pattern
c Flag - Confirm replaces.
& Repeat last :s command
6. Sudo, Sudo user ; Scheduling a re-occurring task ;
Mail server basics
The sudo command
The sudo command stands for "superuser do". It prompts you for your personal
password and confirms your request to execute a command by checking a file,
called sudoers, which the system administrator configures. Using the sudoers
file, system administrators can give certain users or groups access to some
or all commands without those users having to know the root password. It also
logs all commands and arguments so there is a record of who used it for what,
and when.
To use the sudo command, at the command prompt, enter:sudo command
Replace command with the command for which you want to use sudo.
The sudo command also makes it easier to practice the principle of least
privilege (PoLP), which is a computer security concept that helps control
system access and potential system exploits and compromises.
The su command
The su command stands for "switch user", and allows you to become another
user. To use the su command on a per-command basis, enter:
su user -c command
Replace user with the name of the account which you'd like to run the command
as, and command with the command you need to run as another user. To switch
users before running many commands, enter:
su user
Replace user with the name of the account which you'd like to run the
commands as.
The user feature is optional; if you don't provide a user, the su command
defaults to the root account, which in Unix is the system administrator
account. In either case, you'll be prompted for the password associated with
the account for which you're trying to run the command. If you supply a user,
you will be logged in as that account until you exit it. To do so, press
Ctrl-d or type exit at the command prompt.
Scheduling a re-occurring task
Linux Cron utility is an effective way to schedule a routine background job
at a specific time and/or day on an on-going basis.
Crontab –l
Crontab –e
to view the crontab
for editing the crontab.
An example of crontab format with commented fields is as follows:
# Minute
# (0-59)
0
Hour
(0-23)
2
Day of Month
Month
(1-31)
(1-12 or Jan-Dec)
12
*
Day of Week
(0-6 or Sun-Sat)
0, 6
Command
/usr/bin/find
This line executes the "find" command at 2AM on the 12th of every month that
a Sunday or Saturday falls on.
Instead of the first five fields, one of eight special strings may appear:string meaning
@reboot Run once, at startup.
@yearly or Run once a year, "0 0 1 1 *".
@annually
@monthly Run once a month, "0 0 1 * *"
@weekly Run once a week, "0 0 * * 0"
@daily Run once a day, "0 0 * * *"
Or
@midnight
@hourly
Run once an hour, "0 * * * *"
Scheduling a Job For a Specific Time
The basic usage of cron is to execute a job in a specific time as shown
below. This will execute the Full backup shell script (full-backup) on 10th
June 08:30 AM.
Please note that the time field uses 24 hours format. So, for 8 AM use 8, and
for 8 PM use 20.
30 08 10 06 * /home/ramesh/full-backup
• 30 – 30th Minute
• 08 – 08 AM
• 10 – 10th Day
• 06 – 6th Month (June)
• *
– Every day of the week
Schedule a Job For More Than One Instance (e.g. Twice a Day)00 11,16 * * * /home/ramesh/bin/incremental-backup
• 00
–
0th Minute (Top of the hour)
• 11,16 –
11 AM and 4 PM
• *
–
Every day
• *
–
Every month
• *
–
Every day of the week
Schedule a Job for Specific Range of Time (e.g. Only on Weekdays)
Cron Job everyday during working hours
This example checks the status of the database everyday (including weekends)
during the working hours 9 a.m – 6 p.m
00 09-18 * * * /home/ramesh/bin/check-db-status
• 00
– 0th Minute (Top of the hour)
• 09-18 – 9 am, 10 am,11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm
• *
– Every day
• *
– Every month
• *
– Every day of the week
Cron Job every weekday during working hours
This example checks the status of the database every weekday (i.e excluding
Sat and Sun) during the working hours 9 a.m – 6 p.m.
00 09-18 * * 1-5 /home/ramesh/bin/check-db-status
• 00 – 0th Minute (Top of the hour)
• 09-18 – 9 am, 10 am,11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm
• * – Every day
• * – Every month
• 1-5 -Mon, Tue, Wed, Thu and Fri (Every Weekday)
Schedule a Background Cron Job For Every 10 Minutes.
Use the following, if you want to check the disk space every 10 minutes.
*/10 * * * * /home/ramesh/check-disk-spaceMail server basicsMail Systems
In theory, a mail system consists of four different components:
 A “mail user agent”(MUA) that lets user read and compose mail.
 A “mail transport agent”(MTA) that routes messages among machine.
 A “delivery agent” that places messages in a local message store. It is
sometimes called a local delivery agent (LDA).
 An optional “access agent” (AA) that connects he use agent to the
message store (eg., through the IMAP or POP protocol)
How to send a mail from linux
cat |mailx -s "Subject” email_id
type the content
then end it with ctrl+D
How to send a file using mail in linux
Cat filename|mailx –s “Subject” email_id
cat testcore.sh |mailx -s "Hello" arvind.kumar@travelport.com
mail -s "Subject" email_id </dev/null