UNIX Interview Questions

How to print/display the first line of a file?
$> head -1 file.txt
$> sed ‘2,$ d’ file.txt

How to print/display the last line of a file?
$> tail -1 file.txt
$> sed -n ‘$ p’ test

How to display n-th line of a file?
$> sed –n ‘<n> p’ file.txt
$> head -<n> file.txt | tail -1

How to remove the first line / header from a file?
$> sed ‘1 d’ file.txt
$> sed ‘1 d’ file.txt > new_file.txt
$> mv new_file.txt file.txt
$> sed –i ‘1 d’ file.txt

How to remove the last line/ trailer from a file in Unix script?
$> sed –i ‘$ d’ file.txt

How to remove certain lines from a file in Unix?
$> sed –i ‘5,7 d’ file.txt

How to remove the last n-th line from a file?
$> sed –i ‘96,100 d’ file.txt # alternative to command [head -95 file.txt]
$> tt=`wc -l file.txt | cut -f1 -d’ ‘`;sed –i “`expr $tt – 4`,$tt d” test

How to check the length of any line in a file?
$> sed –n ‘<n> p’ file.txt
$> sed –n ’35 p’ file.txt | wc –c​


How to check if a file is present in a particular directory in Unix?
$> ls –l file.txt; echo $?​

How to check all the running processes in Unix?
$> ps –ef
$> ps aux
$>ps -e -o stime,user,pid,args,%mem,%cpu


How to display the 10th line of a file?
head -10 filename | tail -1

How to remove the header from a file?
sed -i ‘1 d’ filename

How to remove the footer from a file?
sed -i ‘$ d’ filename


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


How to get the nth word of a line in Unix?
cut –f<n> -d’ ‘

How to reverse a string in unix?
echo “java” | rev

How to get the last word from a line in Unix file?
echo “unix is good” | rev | cut -f1 -d’ ‘ | rev

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

Write command to list all the links from a directory?
ls -lrt | grep “^l”

How will you find which operating system your system is running on in UNIX?
uname -a

Create a read-only file in your home directory?
touch file; chmod 400 file

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

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