Monday, March 28, 2016

Shell questions


Que : How would you get the character positions 10-20 from a text file?
Ans : cat 1.txt | cut -c 10-20

Que : What id $*, $#, $1, $2..etc (Command line arguments) ?
Ans :
#! /bin/sh

#       $* - prints all the list
#       $# - prints the total number of cmd line args
#       $1 - first cmd line argument

echo $*
echo $#
echo $1

Que : Using Bourne shell : if you enter A B C D E F G.......................n after the command,how will you write a programme to reverse these positional parameters?

#!/bin/sh
#to print arguments in stdin in reverse order
for token in `echo $*| rev`
do
echo $token
done

Que : How would you print just the 25th line in a file (smallest possible script please)?
Ans : sed -n 25p file.txt

Que : How to find how many users have logged in and logged out in last five minutes using shell scripts?
Ans : Who | wc -l | last -5

Que : Write a shell script to identify the given string is palindrome or not?
Ans : use rev function.
echo "$string" >> /temp/file.tmp
rev_str=`rev /temp/file.tmp`;
if [[ "$rev_str" == "$string" ]]

then
        echo palindrome
        else
        echo "non-palindrome"
fi

Que : What does $? return?
Ans : provide exit status of last executed command In case the last command successfully executed then the value is 0 , if its failed to execute then the value non-zero.

Que : What are the different types of shell?
Ans : cat /etc/shells
/bin/sh
/bin/bash
/sbin/nologin
/bin/tcsh
/bin/csh
/bin/dash
/bin/zsh
/bin/mksh
/bin/ksh

Que : Cron entry fields ?
Ans : min hr day month {day of week} year
*/10 * * * * 

Que : Join Two CSV Text Files
Ans : cat file1 file2 > file3

Que : How do you search the string for vowel's occurrence and number of occurrences of each vowel ?
Ans : grep -io [aeiou] filename | wc -w

Que : sed -f scriptname
If you have a large number of sed commands, you can put them into a file and use
sed -f sedscript new
where sedscript could look like this:
If you have many commands and they won't fit neatly on one line, you can break up the line using a backslash:
sed -e 's/a/A/g' \
    -e 's/e/E/g' \
    -e 's/i/I/g' \
    -e 's/o/O/g' \
    -e 's/u/U/g'  new

http://www.grymoire.com/Unix/Sed.html#uh-30

No comments:

Post a Comment