UNIX INTERVIEW QUESTIONS AND ANSWERS – 1

UNIX-INTERVIEW-QUESTIONS-and-ANSWERS-1

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


$ cat file1 file2 file3 > file4

 saving-3-files-into-one-file-using-cat-command

In this way we can use the cat command to concatenate the files and write them into another file.

2.How can I reverse a word like ‘Unix’ to ‘xinU’ ?

We can use rev command to reverse the word.

$ echo “Unix” | rev

reverse-word-using-rev-command

Read also: Unix interview questions and answers part – 2

3.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

reverse-fields-unix-file

If field delimiter is other than space, you need to define it in BEGIN block using FS variable.

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

$ ls -plL | grep -v / | awk 'BEGIN {sum=0} {sum = sum + $5} END {print sum}'

sum-of-file-sizes-unix

ls -plL This command lists everything that isn’t a directory and link (files,device files, etc.)

5.Write a command to print the lines which end with the word “unix”?

$ grep 'unix$' filename

The ‘$’ symbol specifies the grep command to search for the pattern at the end of the line.

word-end-of-the-line-grep-command-unix

Read also: Unix interview questions and answers part – 3

6.Write a command to select only those lines containing “unix” as a whole word?

$ grep -w ‘unix’ filename

grep-command-whole-word-search-unix

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 “unix_os”, the pattern “unix” is found. However “unix” is not a whole word in that string.

7.How to remove the first 2 lines from a file?

$ sed -i '1,2 d' filename

If you want to really delete the first 2 lines from the original file then you can make sed command interactive with the -i option.

This doesn’t echo anything, it will just modify the file in-place. If you don’t need to pipe the result to another command, this is easier.

Or

$ tail -n +3 input_file > output_file

Note that it’s +3 to eliminate first 2 lines, because +3 means “start from line 3” and tail numbers lines from 1.

Or

$ awk 'NR > 2 { print }' < file.txt

grep-awk-sed-commands-to-remove-first-n-lines

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

$ sed 'p' filename

sed-command-duplicate-each-line-unix

9.What happens if use touch command on existing file?

Nothing will happen to the file and that will update the last modified time of the file.

touch-command-unix-on-existing-file

10.How to extract the username from ‘who am i’ command?

$ who am i | cut -f1 -d' '

Comments

comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: