0% found this document useful (0 votes)
175 views18 pages

Unix Interview Questions On Awk Command

This document contains interview questions and answers related to common UNIX commands like awk, grep, sed, and cut. It discusses how to use these commands to process text files, search for patterns, modify text, and extract fields. For example, it explains how to sum the sizes of files in a directory using awk, search for lines containing a word ignoring case with grep, replace text between line numbers with sed, and extract columns delimited by a character with cut.

Uploaded by

Vivek Kushwaha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
175 views18 pages

Unix Interview Questions On Awk Command

This document contains interview questions and answers related to common UNIX commands like awk, grep, sed, and cut. It discusses how to use these commands to process text files, search for patterns, modify text, and extract fields. For example, it explains how to sum the sizes of files in a directory using awk, search for lines containing a word ignoring case with grep, replace text between line numbers with sed, and extract columns delimited by a character with cut.

Uploaded by

Vivek Kushwaha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

3/26/2015

UNIX INTERVIEW QUESTIONS

UNIX INTERVIEW QUESTIONS


UNIXINTERVIEWQUESTIONSONAWKCOMMAND

AwkispowerfultoolinUnix.Awkisanexcellenttoolforprocessingthefileswhichhavedataarrangedin
rowsandcolumnsformat.Itisagoodfilterandreportwriter.
1.Howtorunawkcommandspecifiedinafile?
awkffilename
2.Writeacommandtoprintthesquaresofnumbersfrom1to10usingawkcommand
awk'BEGIN{for(i=1i<=10i++){print"squareof",i,"is",i*i}}'
3.Writeacommandtofindthesumofbytes(sizeoffile)ofallfilesinadirectory.
lsl|awk'BEGIN{sum=0}{sum=sum+$5}END{printsum}'
4.Inthetextfile,somelinesaredelimitedbycolonandsomearedelimitedbyspace.Writeacommandto
printthethirdfieldofeachline.
awk'{if($0~/:/){FS=":"}else{FS=""}print$3}'filename
5.Writeacommandtoprintthelinenumberbeforeeachline?
awk'{printNR,$0}'filename
6.WriteacommandtoprintthesecondandthirdlineofafilewithoutusingNR.
awk'BEGIN{RS=""FS="\n"}{print$2,$3}'filename
7.Writeacommandtoprintzerobytesizefiles?
lsl|awk'/^/{if($5!=0)print$9}'
8.Writeacommandtorenamethefilesinadirectorywith"_new"aspostfix?
lsF|awk'{print"mv"$1""$1".new"}'|sh
9.Writeacommandtoprintthefieldsinatextfileinreverseorder?
awk'BEGIN{ORS=""}{for(i=NFi>0i)print$i,""print"\n"}'filename
10.WriteacommandtofindthetotalnumberoflinesinafilewithoutusingNR
awk'BEGIN{sum=0}{sum=sum+1}END{printsum}'filename
AnotherwaytoprintthenumberoflinesisbyusingtheNR.Thecommandis
awk'END{printNR}'filename

UNIXINTERVIEWQUESTIONSONGREPCOMMAND

Thegrepisoneofthepowerfultoolsinunix.Grepstandsfor"globalsearchforregularexpressionsand
print".Thepowerofgrepliesinusingregularexpressionsmostly.

data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outlin

1/18

3/26/2015

UNIX INTERVIEW QUESTIONS

Thegeneralsyntaxofgrepcommandis
grep[options]pattern[files]
1.Writeacommandtoprintthelinesthathasthethepattern"july"inallthefilesinaparticulardirectory?
grepjuly*
Thiswillprintallthelinesinallfilesthatcontainthewordjulyalongwiththefilename.Ifanyofthefiles
containwordslike"JULY"or"July",theabovecommandwouldnotprintthoselines.
2.Writeacommandtoprintthelinesthathastheword"july"inallthefilesinadirectoryandalso
suppressthefilenameintheoutput.
grephjuly*
3.Writeacommandtoprintthelinesthathastheword"july"whileignoringthecase.
grepijuly*
Theoptionimakethegrepcommandtotreatthepatternascaseinsensitive.
4.Whenyouuseasinglefileasinputtothegrepcommandtosearchforapattern,itwon'tprintthe
filenameintheoutput.Nowwriteagrepcommandtoprintthefilenameintheoutputwithoutusingthe'H'
option.
greppatternfilename/dev/null
The/dev/nullornulldeviceisspecialfilethatdiscardsthedatawrittentoit.So,the/dev/nullisalwaysan
emptyfile.
Anotherwaytoprintthefilenameisusingthe'H'option.Thegrepcommandforthisis
grepHpatternfilename
5.WriteaUnixcommandtodisplaythelinesinafilethatdonotcontaintheword"july"?
grepvjulyfilename
The'v'optiontellsthegreptoprintthelinesthatdonotcontainthespecifiedpattern.
6.Writeacommandtoprintthefilenamesinadirectorythathastheword"july"?
grepljuly*
The'l'optionmakethegrepcommandtoprintonlythefilenamewithoutprintingthecontentofthefile.As
soonasthegrepcommandfindsthepatterninafile,itprintsthepatternandstopssearchingotherlines
inthefile.
7.Writeacommandtoprintthefilenamesinadirectorythatdoesnotcontaintheword"july"?
grepLjuly*
The'L'optionmakesthegrepcommandtoprintthefilenamesthatdonotcontainthespecifiedpattern.
8.Writeacommandtoprintthelinenumbersalongwiththelinethathastheword"july"?
grepnjulyfilename
The'n'optionisusedtoprintthelinenumbersinafile.Thelinenumbersstartfrom1
9.Writeacommandtoprintthelinesthatstartswiththeword"start"?
grep'^start'filename
The'^'symbolspecifiesthegrepcommandtosearchforthepatternatthestartoftheline.

data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outlin

2/18

3/26/2015

UNIX INTERVIEW QUESTIONS

10.Writeacommandtoprintthelineswhichendwiththeword"end"?
grep'end$'filename
The'$'symbolspecifiesthegrepcommandtosearchforthepatternattheendoftheline.
11.Writeacommandtoselectonlythoselinescontaining"july"asawholeword?
grepwjulyfilename
The'w'optionmakesthegrepcommandtosearchforexactwholewords.Ifthespecifiedpatternisfound
inastring,thenitisnotconsideredasawholeword.Forexample:Inthestring"mikejulymak",thepattern
"july"isfound.However"july"isnotawholewordinthatstring.

UNIXINTERVIEWQUESTIONSONSEDCOMMAND

SEDisaspecialeditorusedformodifyingfilesautomatically.
1.Writeacommandtoreplacetheword"bad"with"good"infile?
seds/bad/good/<filename
2.Writeacommandtoreplacetheword"bad"with"good"globallyinafile?
seds/bad/good/g<filename
3.Writeacommandtoreplacethecharacter'/'with','inafile?
sed's/\//,/'<filename
sed's|/|,|'<filename
4.Writeacommandtoreplacetheword"apple"with"(apple)"inafile?
seds/apple/(&)/<filename
5.Writeacommandtoswitchthetwoconsecutivewords"apple"and"mango"inafile?
sed's/\(apple\)\(mango\)/\2\1/'<filename
6.Writeacommandtoreplacethesecondoccurrenceoftheword"bat"with"ball"inafile?
sed's/bat/ball/2'<filename
7.Writeacommandtoremovealltheoccurrencesoftheword"jhon"exceptthefirstonein
alinewithintheentirefile?
sed's/jhon//2g'<filename
8.Writeacommandtoremovethefirstnumberonline5infile?
sed'5s/[09][09]*//'<filename
9.Writeacommandtoremovethefirstnumberonalllinesthatstartwith"@"?
sed'\,^@,s/[09][09]*//'<filename
10.Writeacommandtoreplacetheword"gum"with"drum"inthefirst100linesofafile?
sed'1,00s/gum/drum/'<filename
11.writeacommandtoreplacetheword"lite"with"light"from100thlinetolastlineina
file?
sed'100,$s/lite/light/'<filename

data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outlin

3/18

3/26/2015

UNIX INTERVIEW QUESTIONS

12.Writeacommandtoremovethefirst10linesfromafile?
sed'1,10d'<filename
13.Writeacommandtoduplicateeachlineinafile?
sed'p'<filename
14.Writeacommandtoduplicateemptylinesinafile?
sed'/^$/p'<filename
15.Writeasedcommandtoprintthelinesthatdonotcontaintheword"run"?
sedn'/run/!p'<filename

UNIXINTERVIEWQUESTIONSONCUTCOMMAND

Thecutcommandisusedtousedtodisplayselectedcolumnsorfieldsfromeachlineofa
file.Cutcommandworksintwomodes:
Delimitedselection:Thefieldsinthelinearedelimitedbyasinglecharacterlike
blank,commaetc.
Rangeselection:Eachfieldstartswithcertainfixedoffsetdefinedasrange.
1.Writeacommandtodisplaythethirdandfourthcharacterfromeachlineofafile?
cutc3,4filename
2.Writeacommandtodisplaythecharactersfrom10to20fromeachlineofafile?
cutc1020filename
3.Writeacommandtodisplaythefirst10charactersfromeachlineofafile?
cutc10filename
4.Writeacomamndtodisplayfromthe10thcharactertotheendoftheline?
cutc10filename
5.Thefieldsineachlinearedelimitedbycomma.Writeacommandtodisplaythirdfield
fromeachlineofafile?
cutd','f2filename
6.Writeacommandtoprintthefieldsfrom10to20fromeachlineofafile?
cutd','f1020filename
7.Writeacommandtoprintthefirst5fieldsfromeachline?
cutd','f5filename
8.Writeacommandtoprintthefieldsfrom10thtotheendoftheline?
cutd','f10filename
9.Bydefaultthecutcommanddisplaystheentirelineifthereisnodelimiterinit.Whichcut
optionisusedtosupressthesekindoflines?
Thesoptionisusedtosupressthelinesthatdonotcontainthedelimiter.
10.Writeacutcommandtoextracttheusernamefrom'whoami'comamnd?
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outlin

4/18

3/26/2015

UNIX INTERVIEW QUESTIONS

whoami|cutf1d''

UNIXINTERVIEWQUESTIONSONFINDCOMMAND

Findutilityisusedforsearchingfilesusingthedirectoryinformation.
1.Writeacommandtosearchforthefile'test'inthecurrentdirectory?
findnametesttypef
2.Writeacommandtosearchforthefile'temp'in'/usr'directory?
find/usrnametemptypef
3.Writeacommandtosearchforzerobytesizefilesinthecurrentdirectory?
findsize0typef
4.Writeacommandtolistthefilesthatareaccessed5daysagointhecurrentdirectory?
findatime5typef
5.Writeacommandtolistthefilesthatweremodified5daysagointhecurrentdirectory?
findmtime5typef
6.Writeacommandtosearchforthefilesinthecurrentdirectorywhicharenotownedby
anyuserinthe/etc/passwdfile?
find.nousertypef
7.Writeacommandtosearchforthefilesin'/usr'directorythatstartwith'te'?
find/usrname'te*'typef
8.Writeacommandtosearchforthefilesthatstartwith'te'inthecurrentdirectoryand
thendisplaythecontentsofthefile?
find.name'te*'typefexeccat{}\
9.Writeacommandtolistthefileswhosestatusischanged5daysagointhecurrent
directory?
findctime5typef
10.Writeacommandtolistthefilesin'/usr'directorythatstartwith'ch'andthendisplaythe
numberoflinesineachfile?
find/usrname'ch*'typefexecwcl{}\

TOPUNIXINTERVIEWQUESTIONSPART1

1.Howtodisplaythe10thlineofafile?
head -10 filename | tail -1

2.Howtoremovetheheaderfromafile?
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outlin

5/18

3/26/2015

UNIX INTERVIEW QUESTIONS

sed -i '1 d' filename

3.Howtoremovethefooterfromafile?
sed -i '$ d' filename

4.Writeacommandtofindthelengthofalineinafile?
Thebelowcommandcanbeusedtogetalinefromafile.
sed n '<n> p' filename

Wewillseehowtofindthelengthof10thlineinafile
sed -n '10 p' filename|wc -c

5.HowtogetthenthwordofalineinUnix?
cut f<n> -d' '

6.Howtoreverseastringinunix?
echo "java" | rev

7.HowtogetthelastwordfromalineinUnixfile?
echo "unix is good" | rev | cut -f1 -d' ' | rev

8.HowtoreplacethenthlineinafilewithanewlineinUnix?
sed -i'' '10 d' filename
# d stands for delete
sed -i'' '10 i new inserted line' filename
# i stands for insert

9.HowtocheckifthelastcommandwassuccessfulinUnix?
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outlin

6/18

3/26/2015

UNIX INTERVIEW QUESTIONS

echo $?

10.Writecommandtolistallthelinksfromadirectory?
ls -lrt | grep "^l"

11.HowwillyoufindwhichoperatingsystemyoursystemisrunningoninUNIX?
uname -a

12.Createareadonlyfileinyourhomedirectory?
touch file; chmod 400 file

13.HowdoyouseecommandlinehistoryinUNIX?
The'history'commandcanbeusedtogetthelistofcommandsthatweareexecuted.
14.Howtodisplaythefirst20linesofafile?
Bydefault,theheadcommanddisplaysthefirst10linesfromafile.Ifwechangetheoption
ofhead,thenwecandisplayasmanylinesaswewant.
head -20 filename

Analternativesolutionisusingthesedcommand
sed '21,$ d' filename

Thedoptionheredeletesthelinesfrom21totheendofthefile
15.Writeacommandtoprintthelastlineofafile?
Thetailcommandcanbeusedtodisplaythelastlinesfromafile.
tail -1 filename

Alternativesolutionsare:
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outlin

7/18

3/26/2015

UNIX INTERVIEW QUESTIONS

sed -n '$ p' filename


awk 'END{print $0}' filename

TOPUNIXINTERVIEWQUESTIONSPART2

1.Howdoyourenamethefilesinadirectorywith_newassuffix?
ls -lrt|grep '^-'| awk '{print "mv "$9" "$9".new"}' | sh

2.Writeacommandtoconvertastringfromlowercasetouppercase?
echo "apple" | tr [a-z] [A-Z]

3.WriteacommandtoconvertastringtoInitcap.
echo apple | awk '{print toupper(substr($1,1,1)) tolower(substr($1,2))}'

4.Writeacommandtoredirecttheoutputofdatecommandtomultiplefiles?
Theteecommandwritestheoutputtomultiplefilesandalsodisplaystheoutputonthe
terminal.
date | tee -a file1 file2 file3

5.Howdoyoulistthehiddenfilesincurrentdirectory?
ls -a | grep '^\.'

6.ListoutsomeoftheHotKeysavailableinbashshell?
Ctrl+lClearstheScreen.
Ctrl+rDoesasearchinpreviouslygivencommandsinshell.
Ctrl+uClearsthetypingbeforethehotkey.
Ctrl+aPlacescursoratthebeginningofthecommandatshell.
Ctrl+ePlacescursorattheendofthecommandatshell.
Ctrl+dKillstheshell.
Ctrl+zPlacesthecurrentlyrunningprocessintobackground.
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outlin

8/18

3/26/2015

UNIX INTERVIEW QUESTIONS

7.Howdoyoumakeanexistingfileempty?
cat /dev/null > filename

8.Howdoyouremovethefirstnumberon10thlineinfile?
sed '10 s/[0-9][0-9]*//' < filename

9.Whatisthedifferencebetweenjoinvandjoina?

join -v : outputs only matched lines between two files.


join -a : In addition to the matched lines, this will output unmatched lines also.

10.Howdoyoudisplayfromthe5thcharactertotheendofthelinefromafile?
cut -c 5- filename

TOPUNIXINTERVIEWQUESTIONSPART3

1.Displayallthefilesincurrentdirectorysortedbysize?
ls -l | grep '^-' | awk '{print $5,$9}' |sort -n|awk '{print $2}'

2.Writeacommandtosearchforthefile'map'inthecurrentdirectory?
find -name map -type f

3.Howtodisplaythefirst10charactersfromeachlineofafile?
cut -c -10 filename

4.Writeacommandtoremovethefirstnumberonalllinesthatstartwith"@"?
sed '\,^@, s/[0-9][0-9]*//' < filename
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outlin

9/18

3/26/2015

UNIX INTERVIEW QUESTIONS

5.Howtoprintthefilenamesinadirectorythathastheword"term"?
grep -l term *

The'l'optionmakethegrepcommandtoprintonlythefilenamewithoutprintingthe
contentofthefile.Assoonasthegrepcommandfindsthepatterninafile,itprintsthe
patternandstopssearchingotherlinesinthefile.
6.Howtorunawkcommandspecifiedinafile?
awk -f filename

7.Howdoyoudisplaythecalendarforthemonthmarchintheyear1985?
Thecalcommandcanbeusedtodisplaythecurrentmonthcalendar.Youcanpassthe
monthandyearasargumentstodisplaytherequiredyear,monthcombinationcalendar.
cal 03 1985

ThiswilldisplaythecalendarfortheMarchmonthandyear1985.
8.Writeacommandtofindthetotalnumberoflinesinafile?
wc -l filename

Otherwaystoprintthetotalnumberoflinesare
awk 'BEGIN {sum=0} {sum=sum+1} END {print sum}' filename
awk 'END{print NR}' filename

9.Howtoduplicateemptylinesinafile?
sed '/^$/ p' < filename

10.Explainiostat,vmstatandnetstat?
Iostat:reportsonterminal,diskandtapeI/Oactivity.
Vmstat:reportsonvirtualmemorystatisticsforprocesses,disk,tapeandCPU
activity.
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outli

10/18

3/26/2015

UNIX INTERVIEW QUESTIONS

Netstat:reportsonthecontentsofnetworkdatastructures.

TOPUNIXINTERVIEWQUESTIONSPART4

1.Howdoyouwritethecontentsof3filesintoasinglefile?
cat file1 file2 file3 > file

2.Howtodisplaythefieldsinatextfileinreverseorder?
awk 'BEGIN {ORS=""} { for(i=NF;i>0;i--) print $i," "; print "\n"}' filename

3.Writeacommandtofindthesumofbytes(sizeoffile)ofallfilesinadirectory.
ls -l | grep '^-'| awk 'BEGIN {sum=0} {sum = sum + $5} END {print sum}'

4.Writeacommandtoprintthelineswhichendwiththeword"end"?
grep 'end$' filename

The'$'symbolspecifiesthegrepcommandtosearchforthepatternattheendoftheline.
5.Writeacommandtoselectonlythoselinescontaining"july"asawholeword?
grep -w july filename

The'w'optionmakesthegrepcommandtosearchforexactwholewords.Ifthespecifiedpatternisfound
inastring,thenitisnotconsideredasawholeword.Forexample:Inthestring"mikejulymak",thepattern
"july"isfound.However"july"isnotawholewordinthatstring.
6.Howtoremovethefirst10linesfromafile?
sed '1,10 d' < filename

7.Writeacommandtoduplicateeachlineinafile?
sed 'p' < filename
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outli

11/18

3/26/2015

UNIX INTERVIEW QUESTIONS

8.Howtoextracttheusernamefrom'whoami'comamnd?
who am i | cut -f1 -d' '

9.Writeacommandtolistthefilesin'/usr'directorythatstartwith'ch'andthendisplaythenumberof
linesineachfile?
wc -l /usr/ch*

Anotherwayis
find /usr -name 'ch*' -type f -exec wc -l {} \;

10.Howtoremoveblanklinesinafile?
grep -v ^$ filename > new_filename

TOPUNIXINTERVIEWQUESTIONSPART5

1.Howtodisplaytheprocessesthatwererunbyyourusername?
ps -aef | grep <user_name>

2.Writeacommandtodisplayallthefilesrecursivelywithpathundercurrentdirectory?
find . -depth -print

3.Displayzerobytesizefilesinthecurrentdirectory?
find -size 0 -type f

4.Writeacommandtodisplaythethirdandfifthcharacterfromeachlineofafile?
cut -c 3,5 filename
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outli

12/18

3/26/2015

UNIX INTERVIEW QUESTIONS

5.Writeacommandtoprintthefieldsfrom10thtotheendoftheline.Thefieldsinthelinearedelimited
byacomma?
cut -d',' -f10- filename

6.Howtoreplacetheword"Gun"with"Pen"inthefirst100linesofafile?
sed '1,00 s/Gun/Pen/' < filename

7.WriteaUnixcommandtodisplaythelinesinafilethatdonotcontaintheword"RAM"?
grep -v RAM filename

The'v'optiontellsthegreptoprintthelinesthatdonotcontainthespecifiedpattern.
8.Howtoprintthesquaresofnumbersfrom1to10usingawkcommand
awk 'BEGIN { for(i=1;i<=10;i++) {print "square of",i,"is",i*i;}}'

9.Writeacommandtodisplaythefilesinthedirectorybyfilesize?
ls -l | grep '^-' |sort -nr -k 5

10.HowtofindouttheusageoftheCPUbytheprocesses?
ThetoputilitycanbeusedtodisplaytheCPUusagebytheprocesses.
TOPUNIXINTERVIEWQUESTIONSPART6

1.Writeacommandtoremovetheprefixofthestringendingwith'/'.
Thebasenameutilitydeletesanyprefixendingin/.Theusageismentionedbelow:
basename /usr/local/bin/file

Thiswilldisplayonlyfile
2.Howtodisplayzerobytesizefiles?
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outli

13/18

3/26/2015

UNIX INTERVIEW QUESTIONS

ls -l | grep '^-' | awk '/^-/ {if ($5 !=0 ) print $9 }'

3.Howtoreplacethesecondoccurrenceoftheword"bat"with"ball"inafile?
sed 's/bat/ball/2' < filename

4.Howtoremovealltheoccurrencesoftheword"jhon"exceptthefirstoneinalinewithin
theentirefile?
sed 's/jhon//2g' < filename

5.Howtoreplacetheword"lite"with"light"from100thlinetolastlineinafile?
sed '100,$ s/lite/light/' < filename

6.Howtolistthefilesthatareaccessed5daysagointhecurrentdirectory?
find -atime 5 -type f

7.Howtolistthefilesthatweremodified5daysagointhecurrentdirectory?
find -mtime 5 -type f

8.Howtolistthefileswhosestatusischanged5daysagointhecurrentdirectory?
find -ctime 5 -type f

9.Howtoreplacethecharacter'/'with','inafile?
sed 's/\//,/' < filename
sed 's|/|,|' < filename

10.Writeacommandtofindthenumberoffilesinadirectory.
ls -l|grep '^-'|wc -l
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outli

14/18

3/26/2015

UNIX INTERVIEW QUESTIONS

TOPUNIXINTERVIEWQUESTIONSPART7

1.Writeacommandtodisplayyourname100times.
TheYesutilitycanbeusedtorepeatedlyoutputalinewiththespecifiedstringor'y'.
yes <your_name> | head -100

2.Writeacommandtodisplaythefirst10charactersfromeachlineofafile?
cut -c -10 filename

3.Thefieldsineachlinearedelimitedbycomma.Writeacommandtodisplaythirdfield
fromeachlineofafile?
cut -d',' -f2 filename

4.Writeacommandtoprintthefieldsfrom10to20fromeachlineofafile?
cut -d',' -f10-20 filename

5.Writeacommandtoprintthefirst5fieldsfromeachline?
cut -d',' -f-5 filename

6.Bydefaultthecutcommanddisplaystheentirelineifthereisnodelimiterinit.Whichcut
optionisusedtosuppressthesekindoflines?
Thesoptionisusedtosuppressthelinesthatdonotcontainthedelimiter.
7.Writeacommandtoreplacetheword"bad"with"good"infile?
sed s/bad/good/ < filename

8.Writeacommandtoreplacetheword"bad"with"good"globallyinafile?
sed s/bad/good/g < filename

data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outli

15/18

3/26/2015

UNIX INTERVIEW QUESTIONS

9.Writeacommandtoreplacetheword"apple"with"(apple)"inafile?
sed s/apple/(&)/ < filename

10.Writeacommandtoswitchthetwoconsecutivewords"apple"and"mango"inafile?
sed 's/\(apple\) \(mango\)/\2 \1/' < filename

11.Writeacommandtodisplaythecharactersfrom10to20fromeachlineofafile?
cut -c 10-20 filename

TOPUNIXINTERVIEWQUESTIONSPART8

1.Writeacommandtoprintthelinesthathasthethepattern"july"inallthefilesina
particulardirectory?
grep july *

Thiswillprintallthelinesinallfilesthatcontainthewordjulyalongwiththefilename.If
anyofthefilescontainwordslike"JULY"or"July",theabovecommandwouldnotprint
thoselines.
2.Writeacommandtoprintthelinesthathastheword"july"inallthefilesinadirectory
andalsosuppressthefilenameintheoutput.
grep -h july *

3.Writeacommandtoprintthelinesthathastheword"july"whileignoringthecase.
grep -i july *

Theoptionimakethegrepcommandtotreatthepatternascaseinsensitive.
4.Whenyouuseasinglefileasinputtothegrepcommandtosearchforapattern,itwon't
printthefilenameintheoutput.Nowwriteagrepcommandtoprintthefilenameinthe
outputwithoutusingthe'H'option.
grep pattern file name /dev/null
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outli

16/18

3/26/2015

UNIX INTERVIEW QUESTIONS

The/dev/nullornulldeviceisspecialfilethatdiscardsthedatawrittentoit.So,the/dev/null
isalwaysanemptyfile.
Anotherwaytoprintthefilenameisusingthe'H'option.Thegrepcommandforthisis
grep -H pattern filename

5.Writeacommandtoprintthefilenamesinadirectorythatdoesnotcontaintheword
"july"?
grep -L july *

The'L'optionmakesthegrepcommandtoprintthefilenamesthatdonotcontainthe
specifiedpattern.
6.Writeacommandtoprintthelinenumbersalongwiththelinethathastheword"july"?
grep -n july filename

The'n'optionisusedtoprintthelinenumbersinafile.Thelinenumbersstartfrom1
7.Writeacommandtoprintthelinesthatstartswiththeword"start"?
grep '^start' filename

The'^'symbolspecifiesthegrepcommandtosearchforthepatternatthestartoftheline.
8.Inthetextfile,somelinesaredelimitedbycolonandsomearedelimitedbyspace.Write
acommandtoprintthethirdfieldofeachline.
awk '{ if( $0 ~ /:/ ) { FS=":"; } else { FS =" "; } print $3 }' filename

9.Writeacommandtoprintthelinenumberbeforeeachline?
awk '{print NR, $0}' filename

10.WriteacommandtoprintthesecondandthirdlineofafilewithoutusingNR.

data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outli

17/18

3/26/2015

UNIX INTERVIEW QUESTIONS

awk 'BEGIN {RS="";FS="\n"} {print $2,$3}' filename

11.Howtocreateanaliasforthecomplexcommandandremovethealias?
Thealiasutilityisusedtocreatethealiasforacommand.Thebelowcommandcreates
aliasforpsaefcommand.
alias pg='ps -aef'

Ifyouusepg,itwillworkthesamewayaspsaef.
Toremovethealiassimplyusetheunaliascommandas
unalias pg

12.Writeacommandtodisplaytoday'sdateintheformatof'yyyymmdd'?
Thedatecommandcanbeusedtodisplaytoday'sdatewithtime
date '+%Y-%m-%d'

data:text/html;charset=utf-8,%3Cdiv%20class%3D%22article-header%22%20style%3D%22margin%3A%200px%3B%20outli

18/18

You might also like