Tuesday, September 4, 2012

Write shell script to convert 10 to binary.

#!/bin/sh

binary=({0..1}{0..1}{0..1}{0..1})
echo ${binary[10]}

How could you delete all empty lines from a file within VI?

:g/^$/d
or
:g!/\S/d

Monday, September 3, 2012

How do you get the duplicate/repeated lines in a file in UNIX?

uniq -d <FileName> # print only those lines which are repeated

uniq -c <FileName> # adds the number of occurrences of each line

uniq -u <FileName> # print only those lines which are not at all repeated

What is the substitute to backticks?

"$( )" is the substitute to backticks (``) with an advantage of nesting commands without escapes and better readability. The only bottleneckness $( ) suffers from is lack of portability.

For Example,

VAR=`date +%D`
echo "The date is: $VAR"

or

echo "The date is: `date +%D`"

The above lines can be replaced with the following one :

echo "The date is: $(date +%D)"

How could you close shell keeping all subprocess running?

disown -a && exit

How do you empty or flush all contents of a file without removing it in UNIX?

Prefix the file with ">" and "space" at command line.

> <FileName>

How do you run a command without saving in the history in UNIX?

Prefixing one or more spaces to the command won't be saved in history.
<space> command

How do you wrap text file / line / words to fit in specified width in UNIX?

fold -sw {COUNT} {input.txt} > {output.txt}

Where,
-s: break at spaces.
-w: {COUNT} use COUNT as WIDTH columns instead of default 80.

For instance, following command will wrap input.txt at 70 width columns:

fold -sw 70 input.txt > output.txt

How do you sort a file on a particular column in UNIX?

sort -k2 <FileName>

will be sorted on column 2.

How do you preserve Ownership and Timestamp while copying files in UNIX?

cp -p <source> <destination>