You are on page 1of 15

ITU CSC 505 UNIX / LINUX Operating System Assignment 1

6/20/2016
Please complete this assignment individually and submit in
EMS before July 3rd 2016 11:59pm. Please let me know if you
have any questions. There are 8 questions and corresponding
sub-questions.
1. Explain the effect(s) of the following shell metacharacters
(please be brief):
i.

w ; date
W: check who is logged in; Date: read date

ii.

w > w-out &


check who is log in, and save the results as a file name w-out,
run this process in background

iii.

cal 1 1995 > cal-out ; cal 2 1995 >> cal-out


save 1995 Jan calendar as file cal-out; append the 1995 Feb
calendar onto cal-out file;

iv.

ls | wc -w
list files and folders in the current path, then Count the number of words from ls
output

v.

cat b*
display all the files which file name match regular expression
b*(b can be multiple or none)

vi.

cat ???
display all the files which file name is 3 same characters

vii.

cat [a-z][aeiou]*
display files with name include a letter follow by 0 or multiple
aeiou

viii.

echo $HOME
display the current user home directory

ix.

cat *\?
display file with name ending with a ? mark

2.Writethenameofthecommandwhichwouldaccomplishthefunction.DONOT
provideanyoptions.Thecommandmustbespelledcorrectlyandinthecorrect
case,e.g.WcisnotastandardcommandontheUNIXsystemwcis!
1) Locatefilesanddirectories.
locate,find
2) Condenseafile.
gzip,compress
3) Anotherwaytocondenseafile.
bzip2,zip
4) Createanarchiveoffilesand/ordirectories.
tar
5) Determinehowmuchdiskspaceisbeingusedinyourhomedirectory.
du
6) Displaynonprintingcharactersinafile.
sed,catv,odc
7) Determinethecurrentdateandtime.
date
8) Getalistofloggedinusers.
who
9) Findoutinformationaboutalocalorremoteuser.
finger,id
10)
last

Getalistofyourlastlogins.

11)
Getalistofyourlastbadlogins.
lastb
12)
Changeyourpassword.
passwd
13)
ps

Listallprocesses.

14)

Deleteaprocess.

kill
15)
Runaprocesswhileloggedoff.
nohup
16)
nice

Runaprocessatalowpriority.

17)
ps

Determinetheruntimeofaprocess.

18)
DeterminethevalueoftheshellvariableEDITOR.
echo$EDITOR
19)
Carryonanonlineconversationwithtwoormoreusers.
wall
20)
talk

Carryonanonlineconversationwithoneusers.

21)
Anotherwaytocarryonaconversationwithoneusers.
write
22)
Insureausercannotcarryonaconversationwithyou.
mesgn
23)
Determinewhichportyouarecurrentlyloggedinto.
netstat
24)
Determinethecharacteristicsofyourterminal.
echo$SHELL
3. Write a command to accomplish the task including any
required options, redirections, pipes, or file names.
1. Giveacommandthatwouldrunacommandcalledmybigjobinthebackgroundat
alowpriorityandhavemybigjobcontinuetorunevenafteryouhanguporlog
offthesystem.
nice nohup mybigjob &
2. Giveacommandthatwouldrunacommandcalledimmensejob(notinthe
background)andtellhowlongittooktorun.

immensejob|ps
3. Giveacommandthatwouldkeepotherusers(exceptthesuperuser)fromsending
messagestoyourscreen.
mesgn
4. GiveacommandthatwillsearchtheentireUNIXfiletreeforfileslargerthan
5000blocksinsizeandremovethesefiles.(Assumeyou'rethesuperuser.)
find.size+20kdelete
5. Giveacommandthatwillcreateanarchivecalledodin.tar,placingallfilesina
subdirectorycalledOdinintothearchive.(AssumeOdinisinyourcurrent
directory.)Usethevoption.
tarcvfodin.tar./*
6. Giveacommandthatwillextractafilecalledathena.specfromatararchive
calledspecs.tar.Usethevoption.
tarxvfspecs.tarathena.specs
7. GiveacommandthatwoulddetermineUNIX'snameforthecommunicationsport
orvirtualterminalportyouareusing.
q
8.

Giveacommandthatwouldchangeyourerasecharactertocontrolh.
stty erase "^h"

9.

GiveacommandwhichwoulddisplaytheJuliandate.
calj

10.

Giveacommandwhichwoulddisplayinformationabouttheuserodessaonthehost
machinelawsuitatclark.edu.
fingerOdessa@clark.edu
4. What is accomplished by the following commands:
a. kill -9 13509
-9 forces kernel to kill the process 13509
b. nohup sort time > timeout &
whenloggedoff,keeprunningtheprocessinbackground:sort time >

timeout
c. nice nohup sort time > timeout &
run the process when logged off, keep running the
process in background: sort time > timeoutat a low
priority
d. time cc bigprog.c
Run command/programs or script and summarize system
resource usage, display the time of the execution of the
two commands

e. echo 'Ding\07\nDong\07'
print Ding\07\nDong\07 on the screen
f. mesg n
set mesg to no, disallow other to send message via write
method

g. tty
Print the file name of the terminal connected to standard
input.
h. stty erase "^?"
stty: change and print terminal line settings
erase CHAR: CHAR will erase the last character typed
ctrl+? will be configured as control sequence to eliminate
the last typed character.
5. Answer the following questions about regular expressions. You may test
your answer in UNIX by using:
echo 'testpattern' | grep 'regexp'
For safety, put both testpattern and regexp inside single quotes

Given the following regular expressions, identify those patterns that will be
matched (may be more than one). For those that match, identify which
characters are matched, or explain your reasoning.
1) Regular expression: [ABC]
A
AB
ADBC
D
string with character A,B or C will be a match, therefore A, AB, ADBC will all
match
2) Regular expression: [^ABC]
A
AB
ADBC
D
string with character that is not A,B and C will be a match, therefore ADBC, D will
all match

3) Regular expression: [A-G]


A
AB
MBC
D
string with a character that is between A and G( include A and G) will be a match,
therefore A,AB,MBC , D will all match

4) Regular expression: ^[ABC][AB]$


A
AB

ADBC
D
string with only two letters that starts with a character A,B or C and end with A or
B will be a match, therefore AB is the only match

5) Regular expression: bc.*


aaabbbcccddd
aaaabcsssss
aaaaabc
aabbss
string with bc and 0 or more characters will be a match, therefore aaabbbcccddd
aaaabcsssss
aaaaabc
will all match

6) Regular expression: bc*.


aaabbbcccddd
aaaabcsssss
aaaaabc
aabbss
string with b and 0 or more c and then one character will be a match, therefore
aaabbbcccddd
aaaabcsssss
aaaaabc
aabbss
will all match

7) Regular expression: [^\$]$


$$$$$$aaaaaa
bcdef$
$

abc
string that not ending with $ will be a match, therefore $$$$$$aaaaaa
, abc will match
8) Regular expression: ^[^\$]$
$$$$$$aaaaaa
bcdef$
$
abc
string that with a length of 1 and start with no-$ will be a match, therefore no
match

9) Regular expression: [^\$]$


$$$$$$aaaaaa
bcdef$
$
abc
string that is not end with $ will be a match, therefore
$$$$$$aaaaaa
abc
will match

10) Regular expression: ^\$[0-9][0-9]$


$$$$$$
$10
abc$
$35f
string that starts with $ and then 2 number and end will be a match, therefore
$10

will match

11) Regular expression: ^\$[0-9]*[^0-9]$


$$$$$$
$10
abc$
$35f
string that starts with $ and then 0 or more numbers and then a no-digit
character and end will be a match, therefore
$35f
will match

12) Write a regular expression that matches a line with exactly three characters

13) Write a regular expression that matches a line with at least three characters
.{3,}
14) Write a regular expression that matches a date in the usual format: mm/dd/yy
(0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/] \d{0,4}
15) Write a regular expression that determines the employees who make six digit
salaries in the file emp.lst
\d{6}
6.Hereisupdatedetop2.tarwithfilesandtheproblemsbelow.Untarwithtarxf
top2.tarandremovewith/bin/rmrftop2.Herearesomequestionsaboutthefile
`words'intop2/text/.Readthepage'man5regexp'(mans5regexponsolaris).
Linktotop2.tarhttps://www.dropbox.com/s/3iwk5khhxsx1yhd/top2.tar?dl=0

i.
ii.

A.Usegrep(/bin/greponthemathmachines)wordtopickoutthelinesinthe
wordfilewhichsatisfy:
Blanklines.
grepEn^\s*$words
lineswithatleast3characters

grepEn'[azAZ]{3}'words

iii.

Exactly3lettersfromabc
grepEn'[abc]{3}'words

iv.

Oftheformatnonafollowedby3to5a'sfollowedbyanona
grepEn'[^a]a{3,5}[^a]'words

v.

lineswithoutthepunctuation
grepvn'[[:punct:]]'words

vi.

lineswithanuppercaseletter
grepn'[AZ]'words

vii.

lineswithabcorcbaorbdc
grepEn'abc|cba|bdc'words

B.Usesede's///'wordstochangeallthelinesinwordsfilesothat.
i.
Blanklineschangeto"thislineisintentionallyleftblank"(sans")
sedEe's/^\s*$/thislineisintentionallyleftblank/g'words
ii.

Lineswith3charactersarereplacedwithXXX
sede's/^...$/XXX/g'words

iii.

ReplaceallaorA'swith7
sede's/A/7/g'words

iv.

Replaceallaaa,aaaa,oraaaaawith@
sedEe's/a{3,5}/@/g'words

v.

Replaceuppercaseletterswithperiods
sedEe's/[AZ]/\./g'words

vi.

replaceperiodswithP's
sede's/\./P'\''s/g'words

vii.

replaceaa...astringswith""wheretheaa..aisthesamelengthastheoriginal
sedEe's/aa+a//g'words

7. Explain the following outputs


i.

unix>echoaaaaaaa|sede's/a/X/'
Xaaaaaa
replacethefirstawithX

ii.

unix>echoaaaaaaa|sede's/a*/X/'
X
replaceanylengthofa(0ormore)withX

iii.

unix>echoaaaaaaa|sede's/b*/X/'
Xaaaaaaa
replaceanylengthofb(0ormore)withX

iv.

unix>echoaaaaaaa|sede's/a/X/g'
XXXXXXX
replaceeachawithX

v.

unix>echoaaaaaaa|sede's/aaa/X/g'
XXa
replaceeachaaawithX

vi.

unix>echoaaaaaaa|sede's/a\{3,5\}/X/g'
Xaa
replaceeachaa(lengthatleast3,atmost5)with

X
8. Explain the following unix commands. What will be the
outcome.
1.

echo"`date+%d`>=15"|bc|mails"Paydayyet?"
<emailaddress>
Ifdateislargerthan15,thensendemailwithsubjectpaydayyet?toemail
address.

Thiscommandmainlycreatesanexpressionthat,whenevaluatedbyanother
command,returnswhetherthedateisonorafter15th.
date+%d:Thiscommandwithinbackquotesisgoingtobereplacedwithits
output,whichinturnwillbepartofthestringbeingechoed.Thecommand
printsthedateofthemonth.The"+"signsignifiesthataflaglistfollows,which
willformattheoutputofdate.The%dsignistheflagforthedateofthemonth.
echo"`date+%d`>=15:Printsastringwhichisofthefollowingform:dayofthe
month>=15.Forexample,iftodayisMarch12,thiscommandprints12>=15
bc:Thisisacommandusedforcalculations.Inthiscontext,ittakestheoutput
expressionofthepreviouscommandandprints1ifTrueor0ifFalse
mails"Paydayyet?"<emailaddress>:Sendsanemailtothespecifiedrecepient
withthesubjectas"Paydayyet?".Thebodyistheoutputofbc
2.

grep"^`date+%a`"weekly.txt|mailxs"Today's
tasks"<emailaddress>
findthetasklineinweekly.txtstartwithtoday,andsentemail
Thiscommandsearchesforalinebeginningwithtoday'sdayoftheweekin
weekly.txtandprintsitout.
date+%a
Thiscommandwithinbackquotesisgoingtobereplacedwithitsoutput,which
inturnwillbepartofthestringbeingusedasasearchexpressionbygrep.It
printsthedayoftheweekinanabbreviatedform.SundayisSun,Mondayis
Mon,etc.
"^`date+%a`":Thisregularexpressionsearchesforlinesbeginningwithtoday's
day.Omittingsearchingforthestringinthebeginningofthelinewillhave
unintendedconsequenceslikeselectinglineswhichusethedayofthemonth
elsewhere.
mailxs"Today'stasks"<emailaddress>:Asintheprevioussolution,this
merelysendsanemailwiththesubjectlineas"Today'stasks"tothegivenemail
addresswiththebodybeingtheoutputofgrep.

3.

findcstypefexecgrep\#{}+2>/dev/null|sed
's/.*\///'|trd':#'

findcstypefexecgrep\#{}+2>/dev/null:Thiscommanddoesanumberof
thingsasexplainedbelow:
findcs:findsallfileswithinthecsdirectoryanditssubdirectories.
typef:optioninstructsthefindcommandtolookforonlyfilesandnot
directories.
execgrep\#{}+:partofthecommandusesgreptolookfor#withinthefiles
anditrunsgreponceformultiplefiles.+optionattheendallowsgreptoberun
onceonmultiplefilesinsteadofrunningonceforeachmatchedfile.
2>/dev/null:redirectsallerrors(2representsstandarderrorstream)tothenull
stream.Thishelpstoavoiddisplayofanyerrorsonthestdout.
sed's/.*\///':Sedisusedtoremoveallthedirectorynamesandkeeponlythenet
ids..*\/isaregularexpressionwhichremoveseverythingtillthelast/(slash),
whichresultsindeletionofallthedirectorynamesandonlythefilenames
(NetIds)remain.
trd':#':TheoutputfromthepreviouscommandleavesuswiththeNetIds
followedby":#"(whichisduetotheoutputfromgrepinthefirststep).removes
all":#"fromtheoutput,resultinginthefinalNetIdsofallthestudentswhogot
anA+intheclass.

4. find.typefexecgrepi"^from:"{}\;|grep
Eoi"[AZ09._%+]+@[AZ09.]+\.[AZ]{2,4}"|sort
u&
find.typef:Findallfilesinthecurrect
directoryandallsubdirectories.
execgrepi"^from:"{}\;:Oncefilesarefound,we
aregoingtouseexectorungreponthefiles.
Basically,thisoptionistelling"whenever
youfindafilematchingthecriteriaIgaveyou,
substitute{}withthefilenameandrunthecommand."
Let'ssayfindfoundafilenamed"abc.html".Thenit
willbasicallyrunthisfollowingcommandandputit
ontothepipeline:grepi"^from:"abc.html
Weareusingasemicolonattheend.Why?Youshould
readthisifyouarenotclearwhichoneyoushould
use.

grepEoi"[AZ09._%+]+@[AZ09.]+\.[AZ]{2,4}":
We'regreppingwhat'spassedfromthepreviousfind
command.Eoptionmeansthatwe'llbeusingthe
extendedRegExsyntax.ioptionisforcase
insensitivematching,andooptiondisplaysonly
portionsthatmatch.Nowtotheregularexpression
(source).Thisattemptstomatch"name@domain.suffix"
form.[AZ09._%+]+willmatchoneormorecharacters
thatarealphabets,numbers,oranyofthesespecial
characters:._%+.It'ssimilarwith[AZ09.]+.Then
[AZ]{2,4}matchestwotofourletterlongalphabet
words.Inpractice,theemailaddressformatis
surprisinglycomplex,andthereisnosingleregular
expressionthatcanmatchallvalidemailaddresses
onehundredpercent.Checkouttheseexamples:someof
theaddresseslookliketheyweretypedbycats
walkingonkeybaords,yettheyareallvalidemail
addresses!Wedonotexpectstudentstocomeupwitha
regularexpressionthatmatchesallvalidemail
addresses,soanyreasonableregularexpressionsin
theformof"name@domain"willbeaccptedascorrect
answers.
sortu:Thissortsandlistsonlyuniqueelements.It
createsanidenticalresultas"sort|unique"does.
Wecouldn'tusethisinthepreviousassignment
becauseweneededcoptionforunique:"sort|unique
c".
&:Thisputsthecommandstoruninthebackground.
5. sedE's/(.+,)*([AZaz]+),[AZaz]+;.+/\2/g'
restaurants.txt
EflagdeclarestheusageofextendedRegExp
expressions.
Thisregularexpressionmatches"name,name;"whichare
thetwolastnamesintheparty,togetherwith
everythingthatmaycomebefore,whichiscapturedby
(.+,)*andafterit,namelya;followedbythename
oftherestaurant,capturedby;.+.Notethiscommand
willignorestatementsaboutforeveralonepeoplewho
visitedrestaurantsbythemselves(example:Zulma;Just
ATaste).Itwillsavethesecondtolastnameinthe
registercalled"\2"(weneededtouseparenthesisto

applythestartoperatorin(.+,)*andtheexpression
withinparenthesisgotsavedin\1).Finally,sedwill
substitutethewholelinesthatwerecapturedbythe
regularexpressionwiththevaluestoredinthe
register\2.
6.

grepEo"(\(?[[:digit:]]{3}\)?\s*[.]?\s*)?
[[:digit:]]{3,4}\s*[.]?[[:digit:]]{4}"phonedata.txt
displaythephonenumber(7digitsor10digits)from
thephonedata.txtfile,Eaccesstheextended
regularexpressionsyntax,oonlyoutputthematching
segmentoftheline.
grepEo:Eflagdeclarestheusageofextended
RegExpexpressions.oflagdisplaysonlymatches
(withoutthis,grepwilldisplayawholelinewhen
onlyapartofitcontainsamatch.)
(\(?[[:digit:]]{3}\)?\s*[.]?\s*)?:Thisisfor
matchingtheareacode.?signmeansthatapreceding
literaleitherappearsonlyonceordoesnot
appear.Thewholethingisenclosedin()?becausethe
areacodemaynotappearatall.

You might also like