You are on page 1of 45

IT(R20@II.

B-TechII-Sem) EXP-1

Session-1
A. Login to the system
B. Use‘VI”editortocreateafilecalledmyfile.txtwhichcontainssometext.
C. Correcttypingerrorsduringcreation
D. Savethefile
E. Logoutofthesystem

a.Loginto thesystem
Whenwereturnon thesystemonescreen willappear.Inthis
wehavetotype100.0.0.9thenweenterinto editor.Itasks ourdetails such as
Login:krishnasaip
assword:
Thenwe getlogintothe commands.

b.Usevieditortocreateafilecalledmyfile.txtwhichcontainssometext
Syntax:-vifilename
Description:
 ViCommandisusedtocreate andeditingafile;
 Ifwetype"vifilename".
 Ifthefilenamedfilenameexists,thenthefirstpage(orscreen)ofthefilewillbedisplayed;
 If thefiledoes notexist, thenanemptyfile and screenarecreatedinto whichyou
mayentertext.
Example:vimyfile.text.

c.Correcttypingerrors duringcreation
In creating a file through vi editor an error an error will occur wemodify the file
byopeningthe file again. An error will occur when we don’t give space between filename and
commandname
Example:vikrishnasai

SavetheFile.
Tosavethefile createdinvieditorwepressesc“:WQ”.Itmeansthatsavesthefileand
Quitseditingmode.thenwecomeout from thevi editor.
:wq:-quitvi,writing outmodifiedfileto filenamedin originalinvocation
:q!:-quitvieventhoughlatest changeshavenotbeensavedfor thisvicall
:x:-quitvi,writingoutmodifiedfiletofilenamedinoriginalinvocation

Logoutthesystem.
Syntax: exit
Description:Inourcurrentdirectorypressexittologout fromthe commands

FOSS-LAB
IT(R20@II.B-TechII-Sem) EXP-1

Session-2
A. Logintothesystem
B. Openthefilecreatedinsession-1.
C. Add sometext
D. Changesometext
E. Deletesometext.
F. Savethefile
G. Logoutofthesystem

a.Loginto thesystem
Whenwereturnon thesystemonescreen willappear.Inthis
wehavetotype100.0.0.9thenweenterinto editor.Itasks ourdetails such as
Login:krishnasai
password:
Thenwe getlogintothe commands.

b.Openthefilecreated insession-1
Syntax:vifilename
Inthe abovesession wecreate afileinvieditorToopenthefilecreatedinSession1we
havetotypeasfollows“vifilename”

c.AddSometext:
Toadd sometext tothefilewhich isalreadycreatedfirst wehaveto openthat filethen addtext.
vifilename.Text
The following commands allow you to insert and add text. Each of these commands puts
thevieditorinto insert mode;thus, the<Esc>keymustbepressed to terminatetheentryoftextandto
put thevi editorback into command mode.

 i:-inserttextbeforecursor,until<Esc>hit
 I:-inserttextatbeginningof currentline,until<Esc>hit
 a:-appendtextafter cursor,until<Esc>hit
 A:-appendtexttoend of currentline,until <Esc> hit
 o:-open andput textin anewlinebelowcurrentline, until<Esc>hit
 O:-openandput textinanewlineabovecurrentline,until<Esc>hit

FOSS-LAB
IT(R20@II.B-TechII-Sem) EXP-1

d.ChangingText
Tochangethesometextin myfile.textmovethecursorwherewewant tochangethetextAfterthat replacethetext undercursorw
vimyfile.text
Thefollowingcommands allow you tomodifytext.
 r:-replacesinglecharacterunder cursor (no<Esc>needed)
 R:-replace characters,startingwithcurrentcursor position,until<Esc>hit
 cw:-changethecurrentwordwithnewtext,startingwiththecharacterundercursor,until<Esc>hit
 cNw:-changeN wordsbeginningwithcharacterundercursor,until<Esc> hit;
 e.g.,c5wchanges5words
 C:-change(replace)the charactersinthe currentline,until<Esc>hit
 cc:-change(replace)the entirecurrentline,stoppingwhen<Esc>ishit
 Nccor cNc:-change(replace)thenext Nlines,startingwiththecurrentline,stoppingwhen<Esc>is hit

e.Deletesometext
Todeletetextinmyfiletext wefirst movethecursorto endofthatlineandthen
pressdeletethenthelineis erased todo this firstweopen thefileas
vimyfile.text
Thefollowingcommandsallow youtodeletetext.
 x:-deletesinglecharacterundercursor
 Nx:-deleteNcharacters,startingwith characterundercursor
 dw:-deletethesinglewordbeginningwithcharacterunder cursor
 dNw:-deleteNwordsbeginningwithcharacterundercursor;
 e.g.,d5wdeletes5 words
 D:-deletethe remainder oftheline,startingwithcurrentcursorposition
 dd:-deleteentire currentline
 NddordNd:-deleteNlines,beginningwiththecurrent line;e.g.,5dddeletes5lines

f. Savethechanges:
Tosavethechangesmadeinfilemyfile.textwepressesc:
WQ
Itmeansthat savesthefileand quitseditingmode thenwelogout fromtheviMode.

Logoutthesystem.
Syntax: exit
Description:Inourcurrentdirectorypressexittologout fromthe commands

FOSS-LAB
IT (R20 @II.B-TechII-Sem) EXP-2

A. Logintothesystem
B. Usethe‘cat’commandtocreateafile containingthefollowingdata.Callitmytable
usetabs toseparatethefields.
1425 ravi 15.65
4320 ramu 26.27
6830 sita 36.15
1450 raju 21.86
C. Usethecatcommandtodisplaythefile,mytable.
D. Usethe‘vi’commandtocorrectanyerrorsinthefile,mytable.
E. Usethe‘sort’ commandtosortthefilemytableaccordingtothe firstfield. Callthe
sortedfilemytable(samename)
F. Printthefilemytable.
G. Usethecut andpastecommandsto swapfields2and3 ofmytable.
Callitmytable(Samename)
H. Printthenew, mytable.
I. Logoutofthesystem

FOSS-LAB
IT (R20 @II.B-TechII-Sem) EXP-2

a.Loginto thesystem
Whenwereturnon thesystemonescreen willappear.Inthis
wehavetotype100.0.0.9thenweenterinto editor.Itasks ourdetailssuch as
Login:krishnasaip
assword:
Thenwe getlogintothe commands.

b.Usethecatcommandtocreateafilecontainingthefollowingdata.Callitmytableusetabs
to separatethefields.
1425 Ravi 15.65
4320 Ramu 26.27
6830 Sita 36.15
1450 Raju 21.86
cat>mytable
1425Ravi 15.65
4320Ramu 26.27
6830Sita 36.15
1450Raju 21.86

TosavethefilepressCtrl+DorCtrl+Z

Description:-
CatCommandcanviewthefiledataandcreate anewfileandalsoconcatenatefile
 Creatingfile
Cat>file1.txt
 Creatingonefilefromseveralfiles
catfile1file2file3> file4
This command combines the contents of the first three files into file4. With
thiscommand, file4 is created if it didn't already exist. (Or, it will overwrite file4 if
file4alreadyexisted.)
 Showinglinenumbers
cat -n
myfile.txtcat
myfile-b
Thisprintsthelinenumberbeforeeach linethat isoutput
 appendingonefiletoanotherfile
catfile1>>file2
Appendfile1at the end ofthefile2

c.Usethecatcommandtodisplaythefile,mytable.
$catmytable
1425 Ravi15.65
4320 Ramu26.27
6830 Sita36.15
1450 Raju21.86

FOSS-LAB
IT (R20 @II.B-TechII-Sem) EXP-2

d.Usethevicommand tocorrectany errorsinthefile,mytable


Byusingvieditorwehaveto correcterrors occurredin
creatingfile.Openthefilein vi editoras
Syntax:Vimytable
Usevicommandtocorrecterrors

e.Usethe sort commandto sort thefile mytable according tothefirstfield.Call


thesortedfilemytable
$sort +1 mytable >
mytableOr
$sort-k1mytable >sortfile;cpsortfilemytable
Description:-
Sort:-isa simple andveryusefulcommandwhichwillrearrange thelinesina
textfilesothattheyaresorted, numericallyand alphabetically.

Syntax:sort[OPTION]...[FILE]...

Options

 -b,--ignore-leading-blanks Ignoreleadingblanks.
 -d,--dictionary-orderConsideronlyblanksandalphanumeric characters.
-f,--ignore-case Foldlower casetoupper casecharacters.
 -g,--general-numeric-sort Compareaccordingtogeneralnumericalvalue.
 -i,--ignore-nonprinting Consideronlyprintable characters.
 -M,--month-sort Compare(unknown) < `JAN'<...< `DEC'.
 -h,--human-numeric-sort Comparehumanreadablenumbers(e.g.,"2K","1G").
 -n,--numeric-sort Compareaccordingtostringnumericalvalue.
 -R,--random-sort Sort byrandom hash ofkeys.
 --random-source=FILE GetrandombytesfromFILE.
 -r,--reverse Reversethe resultofcomparisons.
 --sort=WORDSortaccordingtoWORD:general-numeric-g,human-numeric-h,month-M,
numeric-n, random -R, version -V.
 -V,--version-sort Naturalsortof (version)numberswithintext.
Notethatthiscommanddoesnotactuallychangetheinputfile,data.txt.Ifyouwanttowritetheoutput toa
newfile,output.txt,redirectthe outputlikethis:

sortdata.txt>output.txt

Youcanperformareverse-ordersortusingthe-r flag.Forexample,thefollowingcommand:
sort-rdata.txt

FOSS-LAB
IT (R20 @II.B-TechII-Sem) EXP-2
f. Printthefilemytable
catmytable
1425Ravi 15.65
1450Raju 21.86
4320Ramu 26.27
6830Sita 36.15

g.Usethecutandpastecommandstoswapfields2and3of
mytable.Callitmytable(samename)
$cut-f1>mytab1
$cut –f2 >mytab2
$cut –f3>mytab3
$pastemytab3mytab2 >mytab4
$pastemytab1mytab4 >mytable

Description:
Cut
Removeor"cut out"sections ofeach lineofafile orfiles.
Syntax
cutOPTION...[FILE]...
Options
 -b,--bytes=LIST Selectonlythebytesfromeachlineasspecifiedin LIST.
LISTspecifiesabyte,asetof bytes, or arangeofbytes;seeSpecifyingLISTbelow.
 -c, --characters=LISTSelect only the characters from each line as specified in
LIST.LISTspecifiesa character,asetofcharacters,ora rangeof
characters;seeSpecifyingLISTbelow.
 -d,--delimiter=DELIM use character DELIM instead of a tab for the
fielddelimiter.
 -f, --fields=LISTselect only these fields on each line; also print any line
thatcontains no delimiter character, unless the -s option is specified. LIST
specifies afield,asetoffields,ora rangeof fields; seeSpecifyingLISTbelow.
 -n Thisoptionisignored,but isincluded forcompatibilityreasons.
 --complementcomplementthesetofselectedbytes,charactersor fields.
 -s,--only-delimited donotprintlinesnotcontainingdelimiters.
 --output-delimiter=STRINGuseSTRINGastheoutputdelimiterstring.Thedefaultisto
usetheinput delimiter.
To "cut"onlythethird field ofeach line, usethecommand:
cut-f 3data.txt

If instead you want to "cut" only the second-through-fourth field of each line, use
thecommand:
cut-f 2-4data.txt

Ifyouwantto"cut"onlythefirst-through-second andfourth-through-
fifthfieldofeachline(omittingthethird field),usethecommand:
cut-f1-2,4-5data.txt

Ifyouwantthethirdfieldandeveryfieldafterit, omittingthefirsttwofields. Inthiscase,

FOSS-LAB
IT (R20 @II.B-TechII-Sem) EXP-2
youcould usethecommand:
cut-f 3-data.txt

Specifying a range with LIST also applies to cutting characters (-c) or bytes (-b) from a
line.For example, to output only the third-through-twelfth character of every line ofdata.txt,
usethecommand:
cut-c3-12data.txt

pastecommand:
The paste command displays the corresponding lines of multiple files side-by-
side.Syntax:paste[OPTION]... [FILE]...
Examples:pastefile1.txtfile2.txt
Thiscommandwoulddisplay the contentsof file1.txt andfile2.txt,side-by-
side,withthecorrespondinglines ofeach fileseparated byatab.

$ cat
file1Linu
xUnixSol
arisHPU
XAIX

pastecommandwithasinglefile:

1. pastecommandwithoutanyoptionsisasgoodasthecatcommandwhenoperatedonasinglefile.
$ paste
file1Linux
UnixS
olaris
HPUX
AIX

2. Joinalllines inafile:
$paste-sfile1
LinuxUnix SolarisHPUX AIX
-soptionofpastejoinsallthelinesinafile.Sincenodelimiterisspecified,defaultdelimitertabis used to
separatethecolumns.

3. Joinalllines usingthecommadelimiter:
$ paste -d, -s
file1Linux,Unix,Solaris,HPUX,AIX
-doptionisusedtospecifythedelimiter.Usingthis-dand-scombination,allthelinesinthefileget
merged into asingleline.

4. Mergeafile bypastingthedatainto 2columns:


$paste--<file1

FOSS-LAB
IT (R20 @II.B-TechII-Sem) EXP-2
LinuxUnixSol
aris
HPUXAIX
The '-'reads alinefrom thestandard input.Two'-' reads2lines andpastes themsidebyside.

5.Merge a file by pasting the data into 2 columns using a coloum separator:
$ paste -d':' - - <
file1Linux:UnixSolar
is:HPUX
AIX:
This is same as joiningevery2 lines in a file.

6. Merge a file by pasting the file contents into3 columns:


$ paste - - - <
file1LinuxUnix
SolarisHPU
X AIX

7. Merge a fileinto3 columns using 2 different delimiters:


$ paste -d ':,' - - - <
file1Linux:Unix,Solaris
HPUX:AIX,
The-d option can take multiple de-limiters. The 1st and 2nd columns is separated by ':', where as
the 2nd and 3rd are separated by a','.

Paste command examples for multiple files handling

Let us consider a file,file2,with the following contents:


$ cat
file2Suse
FedoraCe
ntOSOEL
Ubuntu

8. Paste contents of2 files side by side.


$ paste file1
file2Linux
SuseUnix
FedoraSo
laris
CentOSHPUX
OEL
AIX Ubuntu
Paste command is used in scenarios to merge multiple files side by side. As shown above,
the file contents are pasted side by side.

FOSS-LAB
IT (R20 @II.B-TechII-Sem) EXP-2
9. pastecontents of2files sidebysidewith acommaseparator:
$ paste -d, file1
file2Linux,SuseUnix
,FedoraSolaris,Cent
OSHPUX,OEL
AIX,Ubuntu

10. Paste command can take standard input in case of multiple files too:
$ cat file2 | paste -d, file1 -
Linux,Suse
Unix,FedoraSo
laris,CentOSH
PUX,OEL
AIX,Ubuntu

Like this as well:


$ cat file1 | paste -d, -
file2Linux,Suse
Unix,FedoraSo
laris,CentOSH
PUX,OEL
AIX,Ubuntu
One more:

$ cat file1 file2 | paste -d, - -


Linux,Unix
Solaris,HPUX
AIX,SuseFedor
a,CentOSOEL,
Ubuntu

11. Read lines in both the files alternatively:


$ paste -d'\n' file1
file2Linux
SuseUn
ixFedor
aSolaris
CentOS
HPUX
OELAI
X
Ubuntu

FOSS-LAB
IT (R20 @II.B-TechII-Sem) EXP-2

H .Print the new file, my table


Cat my table
142515.65 Ravi
145021.86 Raju
432026.27 Ramu
683036.15 Sita

I. Log out the system.


Syntax: exit
Description: In our current directory press exit to log out from the commands

FOSS-LAB
IT (R20@II.B-TechII-Sem) EXP-3

1
a) Logintothesystem
b) Usetheappropriatecommandtodetermineyourloginshell
c) Usethe/etc/passwdfileto verifytheresultofstepb.
d) Usethe‘who’commandandredirecttheresulttoafilecalledmyfile1.Usethemore
commandtoseethecontentsofmyfile1.
e) Use the date and who commands in sequence (in one line) such that the output of
datewill display on the screen and the output of who will be redirected to a file
calledmyfile2.Usethemore command to checkthecontents ofmyfile2.

2
a) Writea“sed”commandthatdeletesthefirst characterineachlineinafile.
b) Writea“sed”commandthatdeletesthecharacterbeforethelastcharacterineachline
inafile.
c) Writea“sed” commandthatswapsthefirstandsecondwordsineachlineinafile.

a.Loginto thesystem
Whenwereturnon thesystemonescreen willappear.Inthis
wehavetotype100.0.0.9thenweenterinto editor.Itasks ourdetails such as
Login:Regdno / Username
password:
Thenwe get logintothecommands.

FOSS-LAB
IT(R20@II.B-TechII-Sem) EXP-3

b.usetheappropriatecommandtodetermineyourloginshell
Syntax:$ echo
$SHELLOutput:$echo$
SHELL
/bin/bash
Description:-
Whatis"theshell"?
Shell is a program that takes your commands from the keyboard and gives them to
theoperating system to perform.In the old days, itwas the only user interface available on
aUnix computer. Nowadays, we have graphical user interfaces (GUIs) in addition to
commandlineinterfaces (CLIs) such as theshell.
On most Linux systems a program called bash (which stands for Bourne Again SHell,
anenhanced version of the original Bourne shell program, sh, written by Steve Bourne) acts
asthe shell program. There are several additional shell programs available on a typical
Linuxsystem.Theseinclude: ksh, tcsh and zsh.

 Tofindyourcurrentshelltypefollowingcommand
$echo$SHELL
 Shell is a user program or it's environment provided for user interaction. Shell is
ancommand language interpreter that executes commands read from the standard
inputdevice(keyboard) orfrom afile.
 Shell is not part of system kernel, but uses the system kernel to execute
programs,createfiles etc.
 SeveralshellavailablewithLinux including:
ShellName Developedby Where Remark
BASH BrianFoxand Free MostcommonshellinLinux.It'sFre
( Bourne- ChetRamey SoftwareFoun ewareshell.
AgainSHell) dation
CSH Bill Joy Universityof TheCshell'ssyntaxandusagearever
(CSHell) California( ysimilarto
ForBSD) theCprogramminglanguage.
KSH DavidKorn AT&TBellLabs --
(KornSHell)
TCSH Seethemanp -- TCSH is an enhanced
age. butcompletelycompatibleversiono
Type$mantcsh f
theBerkeleyUNIXC shell(CSH).

 Tofindallavailableshellsinyoursystemtypefollowingcommand:
$cat/etc/shells

c.usethe/etc/passwdfileto verifytheresultof stepb.


$cat/etc/passwd

FOSS-LAB
IT(R20@II.B-TechII-Sem) EXP-3

d.Usethewhocommandandredirecttheresulttoafilecalledmyfile1.Usethemorecommand
to seethecontents ofmyfile1.
Sol : $who > myfile1 |
moreUser1pts/0 Apr23
10:43
User2 pts/1 May6 18:19

Description:
 Who>myfile1Theresultofwhocommandisstoredinmyfile1
 Moremyfile1Byusingmorecommandweprint themyfile1contents

"who"command:
TheLinux"who"commandletsyoudisplaytheusersthatarecurrentlyloggedintoyourUnixcomputersy
stem.
Syntax:who

On a very busy Unix/Linux system the output of the who command may scroll off
yourterminal screen. To solve that, pipe the output of the who command into the Linux
morecommand,likethis:who |more
The-a argumentofthe whocommandlistsallavailableoutputforeachuser onyoursystem.
who -a
morecommand:
isacommandto view(butnot modify) thecontents ofatext fileonescreen at atime.
Thesyntaxforthemorecommandis:
more [options]
[files]OPTIONS
OptionDescription
 -c Pagethroughthefilebyclearingthewindow.(notscrolling).
 -d Displays "Pressspacetocontinue,'q'toquit"
 -f Countlogicallinesrather thanscreenlines(wrappingtext)
 -l Ignoresformfeed (^L)characters.
 -r Displayall controlcharacters.
 -s Displaysmultipleblanklinesasoneblankline.
 -u Doesnot displayunderlinecharactersand backspace(^H).
 -w Waitsforauserto pressakeybefore exiting.
 -n Displaysnlinesperwindow.
+numDisplays the filestartingat linenumbernum.
+/pattern Displaysthe filestartingattwolinesbeforethepattern.

e.Use the date and who commands in sequence (in one line) such that the output
ofdate will display on the screen and the output ofwho will be redirected to a
filecalledmyfile2. Usethe morecommand tocheckthecontentsofmyfile2.
$date;who>myfile2
SatAug2309:38:05IST 2008
$moremyfile2
allam tty7 2008-08-23 09:08 (:0)
allam pts/1 2008-08-2309:09 (:0.0)
FOSS-LAB
IT(R20@II.B-TechII-Sem) EXP-3

A)Writeasedcommandthatdeletesthefirstcharacterineachlineinafile.
$catmytable
1425 Ravi 15.65
4320 Ramu 26.27
6830 Sita 36.15
1450 Raju 21.86
7820 Anil 23.34
9000 Allam35.56

$sed's/^.//'mytable
425 Ravi 15.65
320 Ramu 26.27
830 Sita 36.15
450 Raju 21.86
820 Anil 23.34
000Allam 35.56

B)Writeasedcommandthatdeletesthecharacterbeforethelastcharacterineachlinein
afile.
#Deletethelastcharacterineachlinein a file.

$sed 's/.$//' mytable


1425 Ravi 15.6
4320 Ramu 26.2
6830 Sita 36.1
1450 Raju 21.8
7820 Anil 23.3
C)Writeased commandthatswaps thefirstandsecondwords inafile.
9000 Allam 35.5
#Swapsthefirst andsecondwordsin eachlineinafile.

$sed ‘s/\([^]*\)*\([^]*\)/\2\1/g’mytable
Ravi 1425 15.65
Ramu 4320 26.27
Sita 6830 36.15
Raju 1450 21.86
Anil 7820 23.34
Allam 9000 35.56

FOSS-LAB
IT(R20@II.B-TechII-Sem) EXP-3
DESCRIPITON
SedisaStreamEditorusedformodifyingthefilesinunix(orlinux).Wheneveryouwanttomakechanges
tothefileautomatically,sed comesin handytodo this.

>catfile.txt

unix is great os. unix is opensource. unix is free


os.learnoperatingsystem.
unixlinuxwhichoneyou choose.

SEDCOMMANDEXAMPLES

1. Replacingor substitutingstring
Sedcommand ismostlyusedto replacethetextin afile. Thebelowsimplesed
commandreplacestheword"unix" with "linux"in thefile.
>sed's/unix/linux/'file.txt
linuxisgreatos.unixisopensource.unixisfreeos.learno
peratingsystem.
linuxlinux whichoneyouchoose.

Herethe "s"specifiesthe substitutionoperation.The"/"aredelimiters.The


"unix"isthesearchpattern and the"linux"is thereplacementstring.

Bydefault,thesedcommand replacesthefirst occurrenceofthepatternin


eachlineanditwon'treplacethesecond,third...occurrencein theline.

2. Replacingthenth occurrenceofapattern in a line.


Usethe/1, /2etcflagstoreplacethefirst,secondoccurrenceofapatterninaline.
Thebelowcommandreplaces thesecond occurrenceoftheword "unix"with "linux"in aline.
>sed 's/unix/linux/2'file.txt
unixisgreatos.linuxisopensource.unixisfreeos.learno
peratingsystem.
unixlinuxwhichoneyou choose.

3. Replacingall theoccurrenceofthepattern in a line.

Thesubstituteflag/g(global replacement)specifiesthesedcommand
toreplacealltheoccurrences ofthestringin theline.
>sed's/unix/linux/g'file.txt
linuxisgreatos.linux
isopensource.linuxisfreeos.learnoperatingsystem.
linuxlinux whichoneyouchoose.

FOSS-LAB
IT(R20@II.B-TechII-Sem) EXP-3

4. Replacingfrom nthoccurrencetoall occurrencesin aline.


Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence
ofapatterninaline.Thefollowingsedcommandreplaces
thethird,fourth,fifth..."unix"wordwith"linux"word in aline.
>sed's/unix/linux/3g'file.txt
unixisgreatos.unix
isopensource.linuxisfreeos.learnoperatingsystem.
unixlinuxwhichoneyou choose.

5. Changingtheslash (/)delimiter
Youcanuse anydelimiterotherthantheslash.Asan exampleif youwanttochangethe weburlto
anotherurl as

>sed's/http:\/\//www/'file.txt

Inthiscasetheurl consiststhedelimitercharacter
whichweused.Inthatcaseyouhavetoescapetheslash withbackslash character,
otherwisethesubstitution won't work.
Using too many backslashes makes the sed command look awkward. In this case we
canchangethedelimiterto anothercharacteras shown in thebelowexample.

>sed's_http://_www_'file.txt
>sed's|http://|www|'file.txt

6. Using&as thematched string

There might be cases where you want to search for the pattern and replace that pattern
byadding some extra characters to it. In such cases & comes in handy. The & represents
thematchedstring.

>sed 's/unix/{&}/'file.txt
{unix} is great os. unix is opensource. unix is free
os.learnoperatingsystem.
{unix}linux whichoneyouchoose.

>sed's/unix/{&&}/'file.txt
{unixunix}isgreatos.unix isopensource.unix
isfreeos.learnoperatingsystem.
{unixunix}linuxwhichoneyou choose.

FOSS-LAB Page6of10
IT(R20@II.B-TechII-Sem) EXP-3

7. Using\1,\2andsoonto\9
The first pair of parenthesis specified in the pattern represents the \1, the second
representsthe \2 and so on. The \1,\2 can be used in the replacement string to make
changes to thesourcestring.Asanexample,if
youwanttoreplacetheword"unix"inalinewithtwiceastheword like"unixunix"usethesed
commandas below.
>sed 's/\(unix\)/\1\1/'file.txt
unixunixisgreatos.unixisopensource.unix
isfreeos.learnoperatingsystem.
unixunixlinux whichoneyouchoose.
Theparenthesisneedstobeescapedwiththebackslashcharacter. Another exampleisifyou
wantto switchthewords"unixlinux"as"linuxunix", thesed commandis
>sed's/\(unix\)\(linux\)/\2\1/'file.txt
unixisgreatos.unix
isopensource.unixisfreeos.learnoperatingsystem.
linuxunixwhichoneyou choose.
Anotherexampleis switchingthefirst threecharacters in aline
>sed's/^\(.\)\(.\)\(.\)/\3\2\1/'file.txt
inuxisgreatos.unix
isopensource.unixisfreeos.aelrnoperatingsystem.
inuxlinuxwhichoneyou choose.

8. Duplicatingthereplacedlinewith /pflag
The/pprintflagprints thereplacedlinetwiceon theterminal.If
alinedoesnothavethesearchpattern and is notreplaced, then the/p prints that lineonlyonce.
>sed 's/unix/linux/p'file.txt
linuxisgreatos.unixisopensource.unixisfreeos.linuxi
sgreatos.unixisopensource.unixisfreeos.learnoperati
ngsystem.
linuxlinuxwhichoneyouchoose.li
nuxlinuxwhichoneyouchoose.

9. Printingonlythereplaced lines
Use the -n option along with the /p print flag to display only the replaced lines. Here the -
noption suppresses the duplicate rows generated by the /p flag and prints the replaced
linesonlyonetime.
>sed-n's/unix/linux/p'file.txt
linuxisgreatos.unixisopensource.unixisfreeos.linuxl
inux which oneyou choose.

Ifyouuse-nalonewithout /p,thentheseddoesnot printanything.

FOSS-LAB Page7of10
IT(R20@II.B-TechII-Sem) EXP-3

10. Runningmultiplesed commands.


You can run multiple sed commands by piping the output of one sed command as input
toanothersedcommand.
>sed's/unix/linux/'file.txt|sed 's/os/system/'
linuxisgreatsystem.unixisopensource.unix
isfreeos.learnoperatingsystem.
linuxlinuxwhichoneyouchosysteme.
Sedprovides-eoption torunmultiplesedcommandsinasinglesedcommand. Theabove
outputcanbeachievedinasinglesed commandasshown below.

>sed-e's/unix/linux/'-e 's/os/system/'file.txt
linuxisgreatsystem.unixisopensource.unix
isfreeos.learnoperatingsystem.
linuxlinuxwhichoneyouchosysteme.

11. Replacingstringonaspecificlinenumber.
Youcanrestrict thesedcommand toreplacethestringonaspecificlinenumber. Anexampleis
>sed'3s/unix/linux/'file.txt
unixisgreatos.unix
isopensource.unixisfreeos.learnoperatingsystem.
linuxlinux whichoneyouchoose.

Theabovesed commandreplaces the stringonlyon thethirdline.

12. Replacingstringonarangeoflines.
Youcanspecifya rangeoflinenumbers tothesedcommandforreplacingastring.
>sed '1,3s/unix/linux/'file.txt
linuxisgreatos.unixisopensource.unixisfreeos.learno
peratingsystem.
linuxlinux whichoneyouchoose.

Herethesed commandreplaces thelines withrangefrom 1to 3. Anotherexampleis


>sed '2,$s/unix/linux/'file.txt
linuxisgreatos.unixisopensource.unixisfreeos.learno
peratingsystem.
linuxlinux whichoneyouchoose.

Here$indicatesthelastlinein thefile.So thesedcommand replacesthetext fromsecondlineto


last linein thefile.

FOSS-LAB Page8of10
IT(R20@II.B-TechII-Sem) EXP-3

13. Replaceonalineswhich matchesapattern.


Youcanspecifyapatterntothesedcommandto matchinaline.Ifthepatternmatchoccurs,then only
the sed command looks for the string to be replaced and if it finds, then the
sedcommandreplaces thestring.
>sed '/linux/s/unix/centos/'file.txt
unixisgreatos.unix
isopensource.unixisfreeos.learnoperatingsystem.
centoslinux whichoneyouchoose.
Herethesedcommandfirstlooksforthelineswhichhasthepattern "linux"andthenreplaces
theword"unix"with"centos".

14. Deletinglines.
You can deletethelinesafilebyspecifyingthelinenumberorarange ornumbers.
>sed'2d'file.txt
>sed'5,$d'file.txt

15. Duplicatinglines
Youcan makethesed command toprint each line ofafiletwotimes.
>sed'p'file.txt

16. Sedasgrepcommand
Youcanmakesedcommandto workassimilartogrep command.
>grep 'unix'file.txt
>sed-n'/unix/p'file.txt

Herethesedcommand looksforthepattern"unix"in eachlineofafileandprints thoselinesthathas


thepattern.
Youcan also makethesed commandto work asgrep-v,
justbyusingthereversingthesedwithNOT(!).
>grep-v'unix'file.txt
>sed-n'/unix/!p'file.txt

The!hereinvertsthepatternmatch.

FOSS-LAB Page9of10
IT(R20@II.B-TechII-Sem) EXP-3
17. Addalineafteramatch.
Thesedcommandcanaddanewlineafter apatternmatchisfound. The "a"commandtosedtellsit to
add anewlineafteramatchisfound.
>sed'/unix/a"Add anewline"'file.txt
unixisgreatos.unix
isopensource.unixisfreeos."Addanewline"
learnoperatingsystem.unixlinux
whichoneyouchoose."Addanewli
ne"

18. Addalinebeforeamatch
Thesedcommandcanaddanewlinebefore apattern matchisfound. The"i"commandtosed tells
it to add anewlinebeforeamatch is found.
>sed'/unix/i"Addanewline"'file.txt"Ad
danewline"
unixisgreatos.unixisopensource.unix
isfreeos.learnoperatingsystem.
"Addanewline"
unixlinuxwhichoneyou choose.

19. Changealine
Thesedcommandcanbe usedtoreplaceanentire linewithanewline.The "c"commandtosedtells
it to changetheline.
>sed'/unix/c"Changeline"'file.txt"C
hangeline"
learnoperatingsystem."
Changeline"

20. Transformliketrcommand
Thesedcommandcanbe used toconvert thelowercaseletterstouppercaseletters
byusingthetransform"y" option.
>sed'y/ul/UL/'file.txt
Unix is great os. Unix is opensoUrce. Unix is free
os.Learnoperatingsystem.
UnixLinUxwhichone yoUchoose.

Herethesed commandtransforms thealphabets"ul"intotheiruppercase format "UL"

FOSS-LAB Page10of10
IT (R20@II.B-Tech II-Sem) EXP-4

4.
a) Pipe your /etc/passwd file to awk, and print out the home directory of each user.

b) Develop an interactive “grep” script that asks for a word and a file name and then tells
how many lines contain that word.

c) Repeat

d) Part using “awk”

a) Pipe your /etc/passwd file to awk, and print out the home directory of each user.

cat /etc/passwd | awk „ { print $7}‟

or

$ vi home.awk
{
if(match ($0, /^.*home/) > 0)
{
split( $0, user)
split(user[1],homedir, ":")
print homedir[1]
}
}

To compile the program use


Sh filename.sh
To return the program

awk command :
$ cat /etc/passwd | awk -f home.awk
Administrator
Guest
sys1
cse
cse123
it
cse501
cse502
it1201
it1202

FOSSLAB
IT (R20@II.B-Tech II-Sem) EXP-4

b) Develop an interactive grep script that asks for a word and a file name and then tells
how many lines contain that word.
Cat>filename
Day by day week by end
Week by week month by end
Month by month year by end
But friendship is never end

$ vi grep.sh
echo "Enter the pattern to be searched: "
read pattern
echo "Enter the file to be used: "
read filename
echo "Searching for $pattern from file $filename"
echo "The selected records are: "
grep "$pattern" $filename
echo "The no.of lines contains the word( $pattern ) :"
grep -c "$pattern" $filename
Output :
$ sh grep.sh
Enter the pattern to be searched:
by
Enter the file to be used:
filename
Searching for by from file sales.dat
The selected records are:
Day by day week by end
Week by week month by end
Month by month year by end
The no. of lines contains the words ( by ) :3

FOSSLAB
IT (R20@II.B-Tech II-Sem) EXP-4
Description:

Awk is one of the most powerful tools in Unix used for processing the rows and columns in a
file. Awk has built in string functions and associative arrays. Awk supports most of the
operators, conditional blocks, and loops available in C language.

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”

One of the good things is that you can convert Awk scripts into Perl scripts using a2p utility.

The basic syntax of AWK:

awk 'BEGIN {start_action} {action} END {stop_action}' filename

Here the actions in the begin block are performed before processing the file and the actions in
the end block are performed after processing the file. The rest of the actions are performed
while processing the file.

Awk Working Methodology


 Awk reads the input files one line at a time.
 For each line, it matches with given pattern in the given order, if matches performs
the corresponding action.
 If no pattern matches, no action will be performed.
 In the above syntax, either search pattern or action are optional, But not both.
 If the search pattern is not given, then Awk performs the given actions for each line of
the input.
 If the action is not given, print all that lines that matches with the given patterns
which is the default action.
 Empty braces with out any action does nothing. It wont perform default printing
operation.
 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 employee.txt
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000

FOSSLAB
IT (R20@II.B-Tech II-Sem) EXP-4
Awk Example 1. Default behavior of Awk
By default Awk prints every line from the file.

$ awk '{print;}' employee.txt


100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $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

FOSSLAB
( IT R20@II.B-Tech II-Sem) EXP-4

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 everyline 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,000
Report 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.

FOSSLAB Page 5 of 8
IT (R20@II.B-Tech II-Sem) EXP-4

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 Tehcnology 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.

To multiply the column-1 and column-2 and redirect the output to file2.txt:
awk '{print $1,$2,$1*$2}' file1.txt > file2.txt

Command Explanation:
$1 :Prints 1st column
$2 :Prints 2ndcolumn
$1*$2 :Prints Result of $1 x $2
file1.txt : input file
> : redirection symbol
file2.txt : output file

GREP
The grep command allows you to search one file or multiple files for lines that contain a
pattern. Exit status is 0 if matches were found, 1 if no matches were found, and 2 if errors
occurred.

SYNTAX
The syntax for the grep command is:

grep [options] pattern [files]

FOSSLAB Page 6 of 8
(IT R20@II.B-Tech II-Sem) EXP-4
OPTIONS
Option Description
-b Display the block number at the beginning of each line.

-c Display the number of matched lines.


-h Display the matched lines, but do not display the filenames.
-i Ignore case sensitivity.

-l Display the filenames, but do not display the matched lines.


-n Display the matched lines and their line numbers.
-s Silent mode.
-v Display all lines that do NOT match.

-w Match whole word.


EXAMPLE
Examples
grep chope /etc/passwd
Search /etc/passwd for user chope.

grep -r "computerhope" /www/


Recursively search the directory /www/, and all subdirectories, for any lines of any files
which contain the string "computerhope".

grep -w "hope" myfile.txt


Search the file myfile.txt for lines containing the word "hope". Only lines containing the
distinct word "hope" will be matched. Lines in which "hope" is part of a word will not be
matched.

grep -cw "hope" myfile.txt


Same as previous command, but displays a count of how many lines were matched, rather
than the matching lines themselves.

grep -cvw "hope" myfile.txt


Inverse of previous command: displays a count of the lines in myfile.txt which do notcontain
the word "hope".

grep -l "hope" /www/*


Display the filenames (but not the matching lines themselves) of any files in /www/(but not
its subdirectories) whose contents include the string "hope".

How do I use grep command to search a file?


Search /etc/passwd file for boo user, enter:
$ grep boo /etc/passwd

Sample outputs:

foo:x:1000:1000:foo,,,:/home/foo:/bin/ksh

FOSSLAB Page 7 of 8
( IT R20@II.B-Tech II-Sem) EXP-4
You can force grep to ignore word case i.e match boo, Boo, BOO and all other combination
with the -i option:
$ grep -i "boo" /etc/passwd

Use grep recursively


You can search recursively i.e. read all files under each directory for a string "192.168.1.5"
$ grep -r "192.168.1.5" /etc/

OR
$ grep -R "192.168.1.5" /etc/

The syntax is as follows:

grep 'word' filename


grep 'word' file1 file2 file3
grep 'string1 string2' filename
cat otherfile | grep 'something'
command | grep 'something'
command option1 | grep 'data'
grep --color 'data' fileName

FOSSLAB Page 8 of 8
IT(R20@II.B-Tech II-Sem) EXP-5
a) Write a shell script that takes a command –line argument and reports on whether it is
directory, a file, or somethingelse.

b) Write a shell script that accepts one or more file name as arguments and converts all of
them touppercase,provided they exist in the currentdirectory.

c) Write a shell script that determines the period for which a specified user is workingon.

a. Write a shell script that takes a command –line argument and reports on whether it is
directory, a file, or something else.

echo " enter file" (or)


read str
if test -f $str $ vi filetype.sh
then echo "file exists n it is an ordinary file" echo "Enter the file name: "
elif test -d $str read file
then echo "directory file" if [ -f $file ]
else
then
echo "not exists"
fi echo $file "---> It is a ORDINARY FILE."
elif [ -d $file]
then
echo $file "---> It is a DIRECTORY."
else
echo $file "---> It is something else."
fi

If condition:

The if...elif...fi statement is the one level advance form of control statement that allows Shell
to make correct decision out of several conditions.
Syntax:
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi

There is nothing special about this code. It is just a series of if statements, where each if is
part of theelse clause of the previous statement. Here statement(s) are executed based on the
true condition, if non of the condition is true then else block isexecuted.

FOSSLAB
IT(R20@II.B-Tech II-Sem) EXP-5

Test:

Checks file types and


compares values. Syntax
test EXPRESSION [ EXPRESSION ]
Description
test is used as part of the conditionalexecution of shellcommands.
test exits with the status determined by EXPRESSION. Placing the EXPRESSION between
square brackets ([ and ]) is the same as testing the EXPRESSION with test. To see the exit
status at the command prompt, echothe value "$?" A value of 0 means the expression
evaluated as true, and a value of 1 means the expression evaluated as false.
Expressions
Expressions take the following forms:
( EXPRESSION) EXPRESSION is true

! EXPRESSION EXPRESSION is false

EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are


true

EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is


true

-n STRING the length of STRING is nonzero

STRING equivalent to -n STRING

-z STRING the length of STRING is zero

STRING1 = STRING2 the strings are equal

STRING1 != STRING2 the strings are not equal

INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2

INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to


INTEGER2

INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2

FOSSLAB
IT(R20@II.B-Tech II-Sem) EXP-5

INTEGER1 -le INTEGER2 INTEGER1 is less than or equal


to INTEGER2

INTEGER1 -lt INTEGER2 INTEGER1 is less than


INTEGER2

INTEGER1 -ne INTEGER2 INTEGER1 is not equal to


INTEGER2

FILE1 -ef FILE2 FILE1 and FILE2


have the same device
and inodenumbers

FILE1 -nt FILE2 FILE1 is newer (modification


date) than FILE2

FILE1 -ot FILE2 FILE1 is older than FILE2

-b FILE FILE exists and is blockspecial

-c FILE FILE exists and is


characterspecial

-d FILE FILE exists and is a directory

-e FILE FILE exists

-f FILE FILE exists and is a regular file

-g FILE FILE exists and is set-group-ID

-G FILE FILE exists


and is owned by the effective
group ID

-h FILE FILE exists and is a symbolic


link(same as -L)

-k FILE FILE exists and has its sticky bit


set

-L FILE FILE exists and is a symbolic


link (same as -h)

-O FILE FILE exists and is owned by the


effective user ID

FOSSLAB
IT(R20@II.B-Tech II-Sem) EXP-5

-p FILE FILE exists and is a named pipe

-r FILE FILE exists and read permissionis granted

-s FILE FILE exists and has a size greater than zero

-S FILE FILE exists and is a socket

-t FD file descriptor FD is opened on a terminal

-u FILE FILE exists and its set-user-ID bit is set

-w FILE FILE exists and write permission is granted

-x FILE FILE exists and execute (or search) permission is g ranted

Except for -h and -L, all FILE-related tests dereference symbolic links. Beware that
parentheses need to be escaped (e.g., by backslashes) for shells. INTEGER may also be-l
STRING, which evaluates to the length of STRING.
NOTE: your shell may have its own version of test, which usually supersedes the version
described here. Please refer to your shell's documentation for details about the options it
supports.
Examples
test 100 -gt 99 && echo "Yes, that's true." || echo "No, that's false."
This command will print the text "Yes, that's true." because 100 is greater than 99.
test 100 -lt 99 && echo "Yes." || echo "No."
This command will print the text "No." because 100 is not less than 99.
[ "awesome" = "awesome" ]; echo $?
This command will print "0" because the expression is true; the two strings are identical.
[ 5 -eq 6 ]; echo $?
This command will print "1" because the expression is false; 5 does not equal 6.

FOSSLAB
IT(R20@II.B-Tech II-Sem) EXP-5

b.Write a shell script that accepts one or more file name as arguments and converts all of
them touppercase,provided they exist in the currentdirectory.

$vi upper.sh # getfilename


for file in * echo -n "Enter File Name : "
do readfileName
# make sure file exits for reading
if [ -f $file ]
if [ ! -f $fileName ]
then then
echo $file | tr '[a-z]''[A-Z]' echo "Filename $fileName does not exists"
fi exit 1
done fi
# convert uppercase to lowercase using tr
command
tr '[A-Z]' '[a-z]' < $fileName

Tr command:
tr - translate or delete characters
Syntax
The syntax of tr command is:

$ tr [OPTION] SET1 [SET2]


Translation
If both the SET1 and SET2 are specified and ‘-d’ OPTION is not specified, then tr command
will replace each characters in SET1 with each character in same position in SET2.
1. Convert lower case to uppercase
The following tr command is used to convert the lower case to upper case

$ tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
thegeekstuff
THEGEEKSTUFF

The following command will also convert lower case to upper case

$ tr [:lower:] [:upper:]
thegeekstuff
THEGEEKSTUFF

You can also use ranges in tr. The following command uses ranges to convert lower to upper
case.

$ tr a-z A-Z
thegeekstuff
THEGEEKSTUFF

FOSSLAB
IT(R20@II.B-Tech II-Sem) EXP-5
2. Translate braces into parenthesis
You can also translate from and to a file. In this example we will translate braces in a file
withparenthesis.

$ tr '{}' '()' < inputfile > outputfile

The above command will read each character from “inputfile”, translate if it is a brace, and
write the output in “outputfile”.
3. Translate white-space totabs
The following command will translate all the white-space to tabs

$ echo "This is for testing" | tr [:space:] '\t'


This is for testing
4. Squeeze repetition of characters using-s
In Example 3, we see how to translate space with tabs. But if there are two are more spaces
present continuously, then the previous command will translate each spaces to a tab as
follows.

$ echo "This is for testing" | tr [:space:] '\t'


This is for testing

We can use -s option to squeeze the repetition of characters.

$ echo "This is for testing" | tr -s [:space:] '\t'


This is for testing
Similarly you can convert multiple continuous spaces with a single space

$ echo "This is for testing" | tr -s [:space:] ' '


This is for testing
5. Delete specified characters using -doption
tr can also be used to remove particular characters using -d option.

$ echo "the geek stuff" | tr -d 't'


he geek suff

To remove all the digits from the string, use

$ echo "my username is 432234" | tr -d [:digit:]


my username is

Also, if you like to delete lines from file, you can use sed d command.

6. Complement the sets using -c option


You can complement the SET1 using -c option. For example, to remove all characters except
digits, you can use the following.

$ echo "my username is 432234" | tr -cd [:digit:]

FOSSLAB Page 6 of 10
IT(R20@II.B-Tech II-Sem) EXP-5

432234

7. Remove all non-printable character from afile


The following command can be used to remove all non-printable characters from a file.

$ tr -cd [:print:] < file.txt


8. Join all the lines in a file into a singleline
The below command will translate all newlines into spaces and make the result as a single
line.

$ tr -s '\n' ' ' < file.txt

c. Write a shell script that determines the period for which a specified user is working on.

echo "Enter the USER NAME : "


readuser
last$user

Output :

$ sh logtime.sh
Enter the USER NAME :
cse123
cse123 tty7 :0 Fri Sep 26
13:27 still loggedin
cse123 pts/1 :0.0 Thu Sep 25
15:08 - 15:45 (00:37)
cse123 tty7 :0 Thu Sep 25
14:53 - 16:32 (01:39)
cse123 tty7 :0 Thu Sep 25
14:13 - 14:25 (00:11)
cse123 tty7 :0 Tue Sep 23
13:54 - 15:30 (01:36)
cse123 pts/2 :20.0 Mon Sep 22
17:02 - 17:23(00:21)

(or)
# w -h root | awk '{print $1,"\t",$3}'
root25Sep0810days
root25Sep0810days
root25Sep0810days

FOSSLAB
IT(R20@II.B-Tech II-Sem) EXP-5

Last command:

The last command reads listing of last logged in users from the system file called
/var/log/wtmp or the file designated by the -f options.

Purpose
To find out when a particular user last logged in to the Linux or Unix server.
Syntax
The basic syntax is:
last
last [userNameHere]
last [tty]
last [options] [userNameHere]
Ifnooptionsprovidedlastcommanddisplaysalistofallusersloggedin(andout)since
/var/log/wtmpfilewascreated.Youcanfilteroutresultsbysupplyingnamesofusersand
tty’s to show only those entries matching the username/tty.
last command examples
To find out who has recently logged in and out on your server, type:
$ last

Sample outputs:

You can specifies a file to search other than /var/log/wtmp using -f option. For example,

oot pts/1 10.1.6.120 Tue Jan 28 05:59 still loggedin


$root
last -f /nas/server/webserver/.log/wtmp
pts/0 10.1.6.120 Tue Jan 28 04:08 still logged in
root pts/0 10.1.6.120 Sat Jan 25 06:33 - 08:55 (02:22)
last -f /nas/server/webserver/.log/wtmp userNameHere
root pts/1 10.1.6.120 Thu Jan 23 14:47 - 14:51 (00:03)
root pts/0 10.1.6.120 Thu Jan 23 13:02 - 14:51 (01:48)
wtmp
root begins
pts/0 Tue 10.1.6.120
Jan 7 12:02:54Tue
2014Jan 7 12:02 - 12:38(00:35)

search /nas/server/webserver/.log/wtmp:

List all users last logged in/out time


last command searches back through the file /var/log/wtmp file and the output may go back
to several months. Just use the less command or more command as follows to display output
one screen at atime:

FOSSLAB
IT(R20@II.B-Tech II-Sem) EXP-5

$ last | more

last | less
List a particular user last logged in
To find out when user vivek last logged in, type:
$ last vivek

$ last vivek |less

$ last vivek | grep 'Thu Jan 23'

For loop
Syntax: for
for var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Here var is the name of a variable and word1 to wordN are sequences of characters separated
by spaces (words). Each time the for loop executes, the value of the variable var is set to the
next word in the list of words, word1 to wordN.
Example:
Here is a simple example that uses for loop to span through the given list of numbers:
#!/bin/sh

for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done

This will produce following result:

0
1
2
3
4
5
6
7
8
9

FOSSLAB
IT(R20@II.B-Tech II-Sem) EXP-5
Following is the example to display all the files starting with .bash and available in your
home. I'm executing this script from my root:
#!/bin/sh

for FILE in $HOME/.bash*


do
echo $FILE
done

This will produce following result:


/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc

FOSSLAB
IT(R20@II.B-Tech II-Sem) EXP-6

a) Write a shell script that accepts a file name starting and ending line numbers as arguments and
displays all the lines between the given line numbers.

b) Write a shell script that deletes all lines containing a specified word in one or more files supplied
as arguments to it.

a. Write a shell script that accepts a file name starting and ending line numbers as arguments
and displays all the lines between the given line numbers.

cat k1
No one is great
no one is waste
without work nothing is possible
with hard work nothing is impossible
so do your work perfectly without fail
[CSESTAFF@localhost foss]$ vi range.sh
echo " Enter the file name :"
read file
if [ -f $file ]
then
echo "Enter the Starting line number:"
read snum
echo "Enter the Ending line number:"
read enum
if [ $snum -lt $enum ]
then
echo "The selected lines from $snum line to $enum line in $file :"
sed -n ''$snum','$enum' 'p'' $file
else
echo "Enter proper starting & ending line numbers."
fi
else
echo "The file ' $file ' doesn't exists. "
fi
output:
[CSESTAFF@localhost foss]$ sh range.sh
Enter the file name : k1
Enter the Starting line number:
2
Enter the Ending line number:
4
The selected lines from 2 line to 4 line in k1 :
no one is waste
without work nothing is possible
with hard work nothing is impossible

FOSSLAB
IT(R20@II.B-Tech II-Sem) EXP-6

b. Write a shell script that deletes all lines containing a specified word in one or more files supplied
as arguments to it.

[CSESTAFF@localhost foss]$ cat k1


No one is great
no one is waste
without work nothing is possible
with hard work nothing is impossible
so do your work perfectly without fail

[CSESTAFF@localhost foss]$ cat k2


hi how are you
tell me about your self
how is the day.

[CSESTAFF@localhost foss]$ vi deleteline.sh


echo "Enter the word to search for all lines :"
read word
echo "the file name are $* ."
for i in $*
do
echo "The name of the file :" $i
grep -v $word $i
done
output:
[CSESTAFF@localhost foss]$ sh deleteline.sh k2 k3
Enter the word to search for all lines :
how
the file name are k2 k3 .
The name of the file : k2
tell me about your self
The name of the file : k3
anything else

FOSSLAB
IT (R20@II.B-Tech II-Sem) EXP-7

a) Write a shell script that computes the gross salary of a employee according to the
following rules:

I. If basic salary is < 1500 then HRA =10% of the basic and DA =90% of the
basic.

II. If basic salary is >=1500 then HRA =Rs500 and DA=98% of the basic

The basic salary is entered interactively through the key board.

b) Write a shell script that accepts two integers as its arguments and computers the value of
first number raised to the power of the second number.

A) Write a shell script that computes the gross salary of a employee according to the
following rules:
I. If basic salary is < 1500 then HRA =10% of the basic and DA =90% of the
basic.
II. If basic salary is >=1500 then HRA =Rs500 and DA=98% of the basic
The basic salary is entered interactively through the key board.
$ vi gsalary.sh
echo "enter the basic salary:"
read bsal
if [ $bsal -lt 1500 ]
then
gsal=$((bsal+((bsal/100)*10)+(bsal/100)*90))
echo "The gross salary : $gsal"
fi
if [ $bsal -ge 1500 ]
then
gsal=$(((bsal+500)+(bsal/100)*98))
echo "the gross salary : $gsal"
fi

Output :

$ sh gsalary.sh
enter the basic salary:
1200
The gross salary : 2400
$ sh gsalary.sh
enter the basic salary:
2400
the gross salary : 5252

Salary: When a person works for someone else or company, (s)he is then said to hold a job
and is called Employee . The person or the company he or she works for is called Employer.
Money that is paid is called as Salary or Income or Wage.

FOSSLAB
IT (R20@II.B-Tech II-Sem) EXP-7
The salary consists of following parts.

Basic Salary: As the name suggests, this forms the very basis of salary. This is the core of
salary, and many other components may be calculated based on this amount. It usually
depends on one’s grade within the company’s salary structure.It is a fixed part of one’s
compensation structure.

Allowance: It is the amount received by an individual paid by his/her employer in addition to


salary to meet some service requirements such as Dearness Allowance(DA), House Rent
Allowance (HRA), Leave Travel Assistance(LTA) , Lunch Allowance, Conveyance
Allowance , Children’s Education Allowance, City compensatory Allowance etc. Allowance
can be fully taxable, partly or non taxable. One can read Understanding the components of
your salary and their taxation for more details.

B) Write a shell script that accepts two integers as its arguments and computers the value
of first number raised to the power of the second number.
[CSESTAFF@localhost foss]$ cat pow.sh
echo "Enter the integer value :"
read int1
echo "Enter the power of that integer:"
read int2
pv=$int1
i=1
while [ $i -lt $int2 ]
do
pv=`expr $pv \* $int1`
i=`expr $i + 1 `
done
echo "The value of first number to the power of the second number :"
echo "$pv"

[CSESTAFF@localhost foss]$ sh pow.sh


Enter the integer value :
6
Enter the power of that integer:
3
The value of first number to the power of the second number :
216

FOSSLAB
IT (R20@II.B-Tech II-Sem) EXP-7

expr command:
Expr command performs arithmetic operations on integers. It can perform the four basic
arithmetic operations, as well as the modulus (remainder function).
$ expr 5 + 10
15
$ a=10 b=5
$ expr $a + $b
15
$ expr $a / $b
2
$ expr $a * $b
expr: syntax error
$ expr $a \* $b
50

Metacharacters
Metacharacters are a group of characters that have special meanings to the UNIX operating
system. Metacharacters can make many tasks easier by allowing you to redirect information
from one command to another or to a file, string multiple commands together on one line, or
have other effects on the commands they are issued in. The following table lists some of the
metacharacters for the Rutgers default shell (the T shell).
Metacharacter Description
UNIX interprets a space as a separator not as a character.
* A wild card character that matches any group of characters of any length,
allowing a user to specify a large group of items with a short string. For
example, to specify all the files that start with 'abc', you use abc*.
? A wild card character that matches any single character. Thus ls ??? lists
files in the current directory whose names are only three characters long,
while ls ???.* lists those files with a three letter main name and any
extension.
[..] A set of characters that can be matched. Thus ls [a-c]*.??? lists all files
that begin with a, b, or c and have a three letter extension and lpr
[ad]* prints all files that begin with a or d.
$ Indicates that the following text is the name of a shell (environment) variable
whose value is to be used.
| Separates commands to form a pipe (see redirection in "Intermediate Use Of
The UNIX Operating System").
< Redirect the standard input (see redirection in "Intermediate Use Of The
UNIX Operating System").
> Redirect the standard output (see redirection in "Intermediate Use Of The
UNIX Operating System") to replace current contents.
>> Redirect the standard output (see redirection in "Intermediate Use Of The

FOSSLAB
IT (R20@II.B-Tech II-Sem) EXP-7

Metacharacter Description
UNIX Operating System") to append to current contents.
>& Redirect the standard output and standard error (see redirection in
"Intermediate Use Of The UNIX Operating System") to replace current
contents.
>>& Redirect the standard output an standard error (see redirection in
"Intermediate Use Of The UNIX Operating System") to append to current
contents.
% Introduces a job name (see multitasking in "Intermediate Use Of The UNIX
Operating System").
& Place a process into the background (see multitasking in "Intermediate Use
Of The UNIX Operating System").
() Encloses a sequence of commands or pipes to be executed as a single
command.
! Precedes a history substitution (see "man history")
; Separates sequences of commands (or pipes) that are on one line.
&& Separates two sequences of commands or pipes the second of which is
executed only if the first succeeds.
|| Separates two sequences of commands or pipes the second of which is
executed only if the first fails.
\ Used to "quote" the following metacharacter so it is treated as a plain
character, as in \*.

FOSSLAB

You might also like