0% found this document useful (0 votes)
577 views

UNIX Interview Questions

The document contains a list of top Unix interview questions organized into multiple parts. It provides answers to common questions asked during Unix interviews such as how to display specific lines from a file, remove headers/footers, find the length of a line, reverse strings, replace lines, check command status, and more. The questions cover topics like file manipulation, string operations, permissions, processes and more.

Uploaded by

utagore58
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
577 views

UNIX Interview Questions

The document contains a list of top Unix interview questions organized into multiple parts. It provides answers to common questions asked during Unix interviews such as how to display specific lines from a file, remove headers/footers, find the length of a line, reverse strings, replace lines, check command status, and more. The questions cover topics like file manipulation, string operations, permissions, processes and more.

Uploaded by

utagore58
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Top Unix Interview Questions - Part 1

1. How to display the 10th line of a file?

head -10 filename | tail -1

2. How to remove the header from a file?

sed -i '1 d' filename

3. How to remove the footer from a file?

sed -i '$ d' filename

4. Write a command to find the length of a line in a file?


The below command can be used to get a line from a file.

sed n '<n> p' filename

We will see how to find the length of 10th line in a file

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

5. How to get the nth word of a line in Unix?

cut f<n> -d' '

6. How to reverse a string in unix?

echo "java" | rev

7. How to get the last word from a line in Unix file?

echo "unix is good" | rev | cut -f1 -d' ' | rev

8. How to replace the n-th line in a file with a new line in Unix?

sed -i'' '10 d' filename

# d stands for delete

sed -i'' '10 i new inserted line' filename

# i stands for insert

9. How to check if the last command was successful in Unix?

echo $?

10. Write command to list all the links from a directory?

ls -lrt | grep "^l"

11. How will you find which operating system your system is running on in UNIX?

uname -a

12. Create a read-only file in your home directory?

touch file; chmod 400 file

13. How do you see command line history in UNIX?


The 'history' command can be used to get the list of commands that we are executed.
14. How to display the first 20 lines of a file?
By default, the head command displays the first 10 lines from a file. If we change the option of head, then we
can display as many lines as we want.

head -20 filename

An alternative solution is using the sed command

sed '21,$ d' filename

The d option here deletes the lines from 21 to the end of the file
15. Write a command to print the last line of a file?
The tail command can be used to display the last lines from a file.

tail -1 filename

Alternative solutions are:

sed -n '$ p' filename


awk 'END{print $0}' filename

Top Unix Interview Questions - Part 2


1. How do you rename the files in a directory with _new as suffix?

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

2. Write a command to convert a string from lower case to upper case?

echo "apple" | tr [a-z] [A-Z]

3. Write a command to convert a string to Initcap.

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

4. Write a command to redirect the output of date command to multiple files?


The tee command writes the output to multiple files and also displays the output on the terminal.

date | tee -a file1 file2 file3

5. How do you list the hidden files in current directory?

ls -a | grep '^\.'

6. List out some of the Hot Keys available in bash shell?


Ctrl+l - Clears the Screen.

Ctrl+r - Does a search in previously given commands in shell.

Ctrl+u - Clears the typing before the hotkey.

Ctrl+a - Places cursor at the beginning of the command at shell.

Ctrl+e - Places cursor at the end of the command at shell.

Ctrl+d - Kills the shell.

Ctrl+z - Places the currently running process into background.


7. How do you make an existing file empty?

cat /dev/null >

filename

8. How do you remove the first number on 10th line in file?

sed '10 s/[0-9][0-9]*//' < filename

9. What is the difference between join -v and join -a?

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


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

10. How do you display from the 5th character to the end of the line from a file?

cut -c 5- filename

Top Unix Interview Questions - Part 3


1. Display all the files in current directory sorted by size?

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

2. Write a command to search for the file 'map' in the current directory?

find -name map -type f

3. How to display the first 10 characters from each line of a file?

cut -c -10 filename

4. Write a command to remove the first number on all lines that start with "@"?

sed '\,^@, s/[0-9][0-9]*//' < filename

5. How to print the file names in a directory that has the word "term"?

grep -l term *

The '-l' option make the grep command to print only the filename without printing the content of the file. As soon
as the grep command finds the pattern in a file, it prints the pattern and stops searching other lines in the file.
6. How to run awk command specified in a file?

awk -f filename

7. How do you display the calendar for the month march in the year 1985?
The cal command can be used to display the current month calendar. You can pass the month and year as
arguments to display the required year, month combination calendar.

cal 03 1985

This will display the calendar for the March month and year 1985.
8. Write a command to find the total number of lines in a file?

wc -l filename

Other ways to print the total number of lines are

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


awk 'END{print NR}' filename

9. How to duplicate empty lines in a file?

sed '/^$/ p' < filename

10. Explain iostat, vmstat and netstat?


Iostat: reports on terminal, disk and tape I/O activity.

Vmstat: reports on virtual memory statistics for processes, disk, tape and CPU activity.

Netstat: reports on the contents of network data structures.

Top Unix Interview Questions - Part 4

1. How do you write the contents of 3 files into a single file?

cat file1 file2 file3 > file

2. How to display the fields in a text file in reverse order?

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


filename

3. Write a command to find the sum of bytes (size of file) of all files in a directory.

ls -l | grep '^-'| awk 'BEGIN {sum=0} {sum = sum + $5} END {print sum}'

4. Write a command to print the lines which end with the word "end"?

grep 'end$' filename

The '$' symbol specifies the grep command to search for the pattern at the end of the line.
5. Write a command to select only those lines containing "july" as a whole word?

grep -w july filename

The '-w' option makes the grep command to search for exact whole words. If the specified pattern is
found in a string, then it is not considered as a whole word. For example: In the string "mikejulymak",
the pattern "july" is found. However "july" is not a whole word in that string.
6. How to remove the first 10 lines from a file?

sed '1,10 d' < filename


7. Write a command to duplicate each line in a file?

sed 'p' < filename

8. How to extract the username from 'who am i' comamnd?

who am i | cut -f1 -d' '

9. Write a command to list the files in '/usr' directory that start with 'ch' and then display the number of
lines in each file?

wc -l /usr/ch*

Another way is

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

10. How to remove blank lines in a file ?

grep -v ^$ filename > new_filename

Top Unix Interview Questions - Part 5

1. How to display the processes that were run by your user name ?

ps -aef | grep <user_name>

2. Write a command to display all the files recursively with path under current directory?

find . -depth -print

3. Display zero byte size files in the current directory?

find -size 0 -type f

4. Write a command to display the third and fifth character from each line of a file?

cut -c 3,5 filename

5. Write a command to print the fields from 10th to the end of the line. The fields in the line are
delimited by a comma?

cut -d',' -f10- filename


6. How to replace the word "Gun" with "Pen" in the first 100 lines of a file?

sed '1,00 s/Gun/Pen/' < filename

7. Write a Unix command to display the lines in a file that do not contain the word "RAM"?

grep -v RAM filename

The '-v' option tells the grep to print the lines that do not contain the specified pattern.
8. How to print the squares of numbers from 1 to 10 using awk command

awk 'BEGIN { for(i=1;i<=10;i++) {print "square of",i,"is",i*i;}}'

9. Write a command to display the files in the directory by file size?

ls -l | grep '^-' |sort -nr -k 5

10. How to find out the usage of the CPU by the processes?
The top utility can be used to display the CPU usage by the processes.

Top Unix Interview Questions - Part 6

1. Write a command to remove the prefix of the string ending with '/'.
The basename utility deletes any prefix ending in /. The usage is mentioned below:

basename /usr/local/bin/file

This will display only file


2. How to display zero byte size files?

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

3. How to replace the second occurrence of the word "bat" with "ball" in a file?

sed 's/bat/ball/2' < filename

4. How to remove all the occurrences of the word "jhon" except the first one in a line with in the entire
file?

sed 's/jhon//2g' < filename


5. How to replace the word "lite" with "light" from 100th line to last line in a file?

sed '100,$ s/lite/light/' < filename

6. How to list the files that are accessed 5 days ago in the current directory?

find -atime 5 -type f

7. How to list the files that were modified 5 days ago in the current directory?

find -mtime 5 -type f

8. How to list the files whose status is changed 5 days ago in the current directory?

find -ctime 5 -type f

9. How to replace the character '/' with ',' in a file?

sed 's/\//,/' < filename


sed 's|/|,|' < filename

10. Write a command to find the number of files in a directory.

ls -l|grep '^-'|wc -l

Top Unix Interview Questions - Part 7

1. Write a command to display your name 100 times.


The Yes utility can be used to repeatedly output a line with the specified string or 'y'.

yes <your_name> | head -100

2. Write a command to display the first 10 characters from each line of a file?

cut -c -10 filename

3. The fields in each line are delimited by comma. Write a command to display third field from each line
of a file?

cut -d',' -f2 filename

4. Write a command to print the fields from 10 to 20 from each line of a file?

cut -d',' -f10-20 filename


5. Write a command to print the first 5 fields from each line?

cut -d',' -f-5 filename

6. By default the cut command displays the entire line if there is no delimiter in it. Which cut option is
used to suppress these kind of lines?
The -s option is used to suppress the lines that do not contain the delimiter.
7. Write a command to replace the word "bad" with "good" in file?

sed s/bad/good/ < filename

8. Write a command to replace the word "bad" with "good" globally in a file?

sed s/bad/good/g < filename

9. Write a command to replace the word "apple" with "(apple)" in a file?

sed s/apple/(&)/ < filename

10. Write a command to switch the two consecutive words "apple" and "mango" in a file?

sed 's/\(apple\) \(mango\)/\2 \1/' < filename

11. Write a command to display the characters from 10 to 20 from each line of a file?

cut -c 10-20 filename

Top Unix Interview Questions - Part 8

1. Write a command to print the lines that has the the pattern "july" in all the files in a particular
directory?

grep july *

This will print all the lines in all files that contain the word july along with the file name. If any of the
files contain words like "JULY" or "July", the above command would not print those lines.
2. Write a command to print the lines that has the word "july" in all the files in a directory and also
suppress the file name in the output.

grep -h july *


3. Write a command to print the lines that has the word "july" while ignoring the case.

grep -i july *

The option i make the grep command to treat the pattern as case insensitive.
4. When you use a single file as input to the grep command to search for a pattern, it won't print the
filename in the output. Now write a grep command to print the file name in the output without using the
'-H' option.

grep pattern file name /dev/null

The /dev/null or null device is special file that discards the data written to it. So, the /dev/null is always
an empty file.
Another way to print the file name is using the '-H' option. The grep command for this is

grep -H pattern filename

5. Write a command to print the file names in a directory that does not contain the word "july"?

grep -L july *

The '-L' option makes the grep command to print the file names that do not contain the specified
pattern.
6. Write a command to print the line numbers along with the line that has the word "july"?

grep -n july filename

The '-n' option is used to print the line numbers in a file. The line numbers start from 1
7. Write a command to print the lines that starts with the word "start"?

grep '^start' filename

The '^' symbol specifies the grep command to search for the pattern at the start of the line.
8. In the text file, some lines are delimited by colon and some are delimited by space. Write a
command to print the third field of each line.

awk '{ if( $0 ~ /:/ ) { FS=":"; } else { FS =" "; } print $3 }' filename

9. Write a command to print the line number before each line?

awk '{print NR, $0}' filename

10. Write a command to print the second and third line of a file without using NR.

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

11. How to create an alias for the complex command and remove the alias?
The alias utility is used to create the alias for a command. The below command creates alias for ps
-aef command.

alias pg='ps -aef'

If you use pg, it will work the same way as ps -aef.


To remove the alias simply use the unalias command as

unalias pg

12. Write a command to display today's date in the format of 'yyyy-mm-dd'?


The date command can be used to display today's date with time

date '+%Y-%m-%d'

Find Command in Unix and Linux Examples

Find is one of the powerful utility of Unix (or Linux) used for searching the files in a directory hierarchy.
The syntax of find command is

find [pathnames] [conditions]

Let see some practical exercises on using find command.


1. How to run the last executed find command?

!find

This will execute the last find command. It also displays the last find command executed along with the
result on the terminal.
2. How to find for a file using name?

find -name "sum.java"


./bkp/sum.java
./sum.java

This will find all the files with name "sum.java" in the current directory and sub-directories.
3. How to find for files using name and ignoring case?

find -iname "sum.java"


./SUM.java
./bkp/sum.java
./sum.java

This will find all the files with name "sum.java" while ignoring the case in the current directory and subdirectories.
4. How to find for a file in the current directory only?

find -maxdepth 1 -name "sum.java"


./sum.java

This will find for the file "sum.java" in the current directory only
5. How to find for files containing a specific word in its name?

find -name "*java*"


./SUM.java
./bkp/sum.java
./sum.java
./multiply.java

It displayed all the files which have the word "java" in the filename
6. How to find for files in a specific directory?

find /etc -name "*java*"

This will look for the files in the /etc directory with "java" in the filename
7. How to find the files whose name are not "sum.java"?

find -not -name "sum.java"


.
./SUM.java
./bkp
./multiply.java

This is like inverting the match. It prints all the files except the given file "sum.java".
8. How to limit the file searches to specific directories?

find -name "sum.java"


./tmp/sum.java
./bkp/var/tmp/files/sum.java
./bkp/var/tmp/sum.java
./bkp/var/sum.java
./bkp/sum.java
./sum.java

You can see here the find command displayed all the files with name "sum.java" in the current directory
and sub-directories.
a. How to print the files in the current directory and one level down to the current directory?

find -maxdepth 2 -name "sum.java"


./tmp/sum.java
./bkp/sum.java
./sum.java

b. How to print the files in the current directory and two levels down to the current directory?

find -maxdepth 3 -name "sum.java"


./tmp/sum.java
./bkp/var/sum.java
./bkp/sum.java
./sum.java

c. How to print the files in the subdirectories between level 1 and 4?

find -mindepth 2 -maxdepth 5 -name "sum.java"


./tmp/sum.java

./bkp/var/tmp/files/sum.java
./bkp/var/tmp/sum.java
./bkp/var/sum.java
./bkp/sum.java

9. How to find the empty files in a directory?

find . -maxdepth 1 -empty


./empty_file

10. How to find the largest file in the current directory and sub directories

find . -type f -exec ls -s {} \; | sort -n -r | head -1

The find command "find . -type f -exec ls -s {} \;" will list all the files along with the size of the file. Then
the sort command will sort the files based on the size. The head command will pick only the first line
from the output of sort.
11. How to find the smallest file in the current directory and sub directories

find . -type f -exec ls -s {} \; | sort -n -r | tail -1

Another method using find is

find . -type f -exec ls -s {} \; | sort -n

12. How to find files based on the file type?


a. Finding socket files

find . -type s

b. Finding directories

find . -type d

c. Finding hidden directories

| head -1

find -type d -name ".*"

d. Finding regular files

find . -type f

e. Finding hidden files

find . -type f -name ".*"

13. How to find files based on the size?


a. Finding files whose size is exactly 10M

find . -size 10M

b. Finding files larger than 10M size

find . -size +10M

c. Finding files smaller than 10M size

find . -size -10M

14. How to find the files which are modified after the modification of a give file.

find -newer "sum.java"

This will display all the files which are modified after the file "sum.java"
15. Display the files which are accessed after the modification of a give file.

find -anewer "sum.java"

16. Display the files which are changed after the modification of a give file.

find -cnewer "sum.java"

17. How to find the files based on the file permissions?

find . -perm 777

This will display the files which have read, write, and execute permissions. To know the permissions of
files and directories use the command "ls -l".
18. Find the files which are modified within 30 minutes.

find . -mmin -30

19. Find the files which are modified within 1 day.

find . -mtime -1

20. How to find the files which are modified 30 minutes back

find . -not -mmin -30

21. How to find the files which are modified 1 day back.

find . -not -mtime -1

22. Print the files which are accessed within 1 hour.

find . -amin -60

23. Print the files which are accessed within 1 day.

find . -atime -1

24. Display the files which are changed within 2 hours.

find . -cmin -120


25. Display the files which are changed within 2 days.

find . -ctime -2

26. How to find the files which are created between two files.

find . -cnewer f1 -and ! -cnewer f2

So far we have just find the files and displayed on the terminal. Now we will see how to perform some
operations on the files.
1. How to find the permissions of the files which contain the name "java"?

find -name "*java*"|xargs ls -l

Alternate method is

find -name "*java*" -exec ls -l {} \;

2. Find the files which have the name "java" in it and then display only the files which have "class" word
in them?

find -name "*java*" -exec grep -H class {} \;

3. How to remove files which contain the name "java".

find -name "*java*" -exec rm -r {} \;

This will delete all the files which have the word java" in the file name in the current directory and subdirectories.
Similarly you can apply other Unix commands on the files found using the find command. I will add
more examples as and when i found.
If you like this post, then please share it on Google by clicking on the +1 button.

Top Examples of Awk Command in Unix

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.
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.
Examples:
Create a file input_file with the following data. This file can be easily created using the output of ls -l.

-rw-r--r-- 1 center center

0 Dec

8 21:39 p1

-rw-r--r-- 1 center center 17 Dec

8 21:15 t1

-rw-r--r-- 1 center center 26 Dec

8 21:38 t2

-rw-r--r-- 1 center center 25 Dec

8 21:38 t3

-rw-r--r-- 1 center center 43 Dec

8 21:39 t4

-rw-r--r-- 1 center center 48 Dec

8 21:39 t5

From the data, you can observe that this file has rows and columns. The rows are separated by a new line
character and the columns are separated by a space characters. We will use this file as the input for the
examples discussed here.
1. awk '{print $1}' input_file
Here $1 has a meaning. $1, $2, $3... represents the first, second, third columns... in a row respectively. This
awk command will print the first column in each row as shown below.

-rw-r--r--rw-r--r--rw-r--r--rw-r--r--rw-r--r--rw-r--r--

To print the 4th and 6th columns in a file use awk '{print $4,$5}' input_file
Here the Begin and End blocks are not used in awk. So, the print command will be executed for each row it
reads from the file. In the next example we will see how to use the Begin and End blocks.
2. awk 'BEGIN {sum=0} {sum=sum+$5} END {print sum}' input_file
This will prints the sum of the value in the 5th column. In the Begin block the variable sum is assigned with
value 0. In the next block the value of 5th column is added to the sum variable. This addition of the 5th column
to the sum variable repeats for every row it processed. When all the rows are processed the sum variable will
hold the sum of the values in the 5th column. This value is printed in the End block.
3. In this example we will see how to execute the awk script written in a file. Create a file sum_column and
paste the below script in that file

#!/usr/bin/awk -f
BEGIN {sum=0}
{sum=sum+$5}
END {print sum}

Now execute the the script using awk command as


awk -f sum_column input_file.
This will run the script in sum_column file and displays the sum of the 5th column in the input_file.
4. awk '{ if($9 == "t4") print $0;}' input_file

This awk command checks for the string "t4" in the 9th column and if it finds a match then it will print the entire
line. The output of this awk command is

-rw-r--r-- 1 pcenter pcenter 43 Dec

8 21:39 t4

5. awk 'BEGIN { for(i=1;i<=5;i++) print "square of", i, "is",i*i; }'


This will print the squares of first numbers from 1 to 5. The output of the command is

square of 1 is 1
square of 2 is 4
square of 3 is 9
square of 4 is 16
square of 5 is 25

Notice that the syntax of if and for are similar to the C language.
Awk Built in Variables:
You have already seen $0, $1, $2... which prints the entire line, first column, second column... respectively. Now
we will see other built in variables with examples.
FS - Input field separator variable:
So far, we have seen the fields separted by a space character. By default Awk assumes that fields in a file are
separted by space characters. If the fields in the file are separted by any other character, we can use the FS
variable to tell about the delimiter.
6. awk 'BEGIN {FS=":"} {print $2}' input_file
OR
awk -F: '{print $2} input_file
This will print the result as

39 p1

15 t1
38 t2
38 t3
39 t4
39 t5

OFS - Output field separator variable:


By default whenever we printed the fields using the print statement the fields are displayed with space character
as delimiter. For example
7. awk '{print $4,$5}' input_file
The output of this command will be

center 0
center 17
center 26
center 25
center 43
center 48

We can change this default behavior using the OFS variable as


awk 'BEGIN {OFS=":"} {print $4,$5}' input_file

center:0
center:17
center:26

center:25
center:43
center:48

Note: print $4,$5 and print $4$5 will not work the same way. The first one displays the output with space as
delimiter. The second one displays the output without any delimiter.
NF - Number of fileds variable:
The NF can be used to know the number of fields in line
8. awk '{print NF}' input_file
This will display the number of columns in each row.
NR - number of records variable:
The NR can be used to know the line number or count of lines in a file.
9. awk '{print NR}' input_file
This will display the line numbers from 1.
10. awk 'END {print NR}' input_file
This will display the total number of lines in the file.
String functions in Awk:
Some of the string functions in awk are:
index(string,search)
length(string)
split(string,array,separator)
substr(string,position)
substr(string,position,max)
tolower(string)
toupper(string)
Advanced Examples:
1. Filtering lines using Awk split function
The awk split function splits a string into an array using the delimiter.
The syntax of split function is
split(string, array, delimiter)
Now we will see how to filter the lines using the split function with an example.

The input "file.txt" contains the data in the following format

1 U,N,UNIX,000
2 N,P,SHELL,111
3 I,M,UNIX,222
4 X,Y,BASH,333
5 P,R,SCRIPT,444

Required output: Now we have to print only the lines in which whose 2nd field has the string "UNIX" as the 3rd
field( The 2nd filed in the line is separated by comma delimiter ).
The ouptut is:

1 U,N,UNIX,000
3 I,M,UNIX,222

The awk command for getting the output is:

awk '{
split($2,arr,",");
if(arr[3] == "UNIX")
print $0
} ' file.txt

You might also like