Unix interview questions and answers

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



Post a Comment

If you have any doubts, Please let me know
Thanks!

Previous Post Next Post