Foss LAB MANUAL
Foss LAB MANUAL
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([email protected]) 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([email protected]) 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
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
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.
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.
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
FOSS-LAB
IT (R20 @II.B-TechII-Sem) EXP-2
FOSS-LAB
IT ([email protected]) 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([email protected]) 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
FOSS-LAB
IT([email protected]) EXP-3
d.Usethewhocommandandredirecttheresulttoafilecalledmyfile1.Usethemorecommand
to seethecontents ofmyfile1.
Sol : $who > myfile1 |
moreUser1pts/0 Apr23
10:43
User2 pts/1 May6 18:19
Description:
Who>myfile1Theresultofwhocommandisstoredinmyfile1
Moremyfile1Byusingmorecommandweprint 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([email protected]) 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/\([^]*\)*\([^]*\)/\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([email protected]) EXP-3
DESCRIPITON
SedisaStreamEditorusedformodifyingthefilesinunix(orlinux).Wheneveryouwanttomakechanges
tothefileautomatically,sed comesin handytodo this.
>catfile.txt
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.
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([email protected]) EXP-3
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
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([email protected]) 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.
FOSS-LAB Page7of10
IT([email protected]) EXP-3
>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.
12. Replacingstringonarangeoflines.
Youcanspecifya rangeoflinenumbers tothesedcommandforreplacingastring.
>sed '1,3s/unix/linux/'file.txt
linuxisgreatos.unixisopensource.unixisfreeos.learno
peratingsystem.
linuxlinux whichoneyouchoose.
FOSS-LAB Page8of10
IT([email protected]) EXP-3
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
The!hereinvertsthepatternmatch.
FOSS-LAB Page9of10
IT([email protected]) 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.
FOSS-LAB Page10of10
IT ([email protected] 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
a) Pipe your /etc/passwd file to awk, and print out the home directory of each user.
or
$ vi home.awk
{
if(match ($0, /^.*home/) > 0)
{
split( $0, user)
split(user[1],homedir, ":")
print homedir[1]
}
}
awk command :
$ cat /etc/passwd | awk -f home.awk
Administrator
Guest
sys1
cse
cse123
it
cse501
cse502
it1201
it1202
FOSSLAB
IT ([email protected] 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 ([email protected] 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.
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.
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 ([email protected] II-Sem) EXP-4
Awk Example 1. Default behavior of Awk
By default Awk prints every line from the file.
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.
FOSSLAB
( IT [email protected] 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.
Syntax:
BEGIN { Actions}
{ACTION} # Action for everyline in a file
END { Actions }
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.
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
FOSSLAB Page 5 of 8
IT ([email protected] II-Sem) EXP-4
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:
FOSSLAB Page 6 of 8
(IT [email protected] II-Sem) EXP-4
OPTIONS
Option Description
-b Display the block number at the beginning of each line.
Sample outputs:
foo:x:1000:1000:foo,,,:/home/foo:/bin/ksh
FOSSLAB Page 7 of 8
( IT [email protected] 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
OR
$ grep -R "192.168.1.5" /etc/
FOSSLAB Page 8 of 8
IT([email protected] 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.
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([email protected] II-Sem) EXP-5
Test:
FOSSLAB
IT([email protected] II-Sem) EXP-5
FOSSLAB
IT([email protected] II-Sem) EXP-5
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([email protected] 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.
Tr command:
tr - translate or delete characters
Syntax
The syntax of tr command is:
$ 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([email protected] 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.
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
Also, if you like to delete lines from file, you can use sed d command.
FOSSLAB Page 6 of 10
IT([email protected] II-Sem) EXP-5
432234
c. Write a shell script that determines the period for which a specified user is working on.
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([email protected] 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,
search /nas/server/webserver/.log/wtmp:
FOSSLAB
IT([email protected] 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
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
0
1
2
3
4
5
6
7
8
9
FOSSLAB
IT([email protected] 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
FOSSLAB
IT([email protected] 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([email protected] 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.
FOSSLAB
IT ([email protected] 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
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 ([email protected] 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.
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"
FOSSLAB
IT ([email protected] 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 ([email protected] 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