Shell

For Loop
#!/bin/sh
for FILE in $HOME/.bash*
do
echo $FILE
done

for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo “$var1 $var2”
fi
done
done

Rename Using Sheds
for file in * ; do mv — “$file” “${file//0*3/ke}” ; done
for f in * ; do mv “$f” “${f}_N” ; done ;

Get the directory path of file
find . -print “%h\n”

One line condition and trigger
[ -d ${C_MEMENTO_BACKUP}/${country}/CACS/Build/day_${day} ] || do_command mkdir -p ${C_MEMENTO_BACKUP}/${country}/CACS/Build/day_${day}

Condition to check ZERO length
if [ ! -z “${ext}” ]; then
fi

Length of array
${#arrayObj[@]}

using Count
(( count++ ))

Reading file and looping
while read p; do
echo $p
done <iso.txt

get Filename and extension
filename=`basename $file`
extension="${filename##*.}"
filename="${filename%.*}"

Get all files from directories
find path/*

Get the folder size
du -h folder

get the folder size and not sub folder
du -hs folder

get no.of lines in file
wc -l

Find files / scripts that don’t have CR no
find . -type f | xargs grep -H -c 'CRQ000000203849' | grep 0$ | cut -d':' -f1
find . -type f -exec grep -H -c 'shared.php' {} \; | grep 0$ | cut -d':' -f1
Here we are calculating number of matching lines(using -c) in a file if the count is 0 then its the required file, so we cut the first column i.e. filename from the output.

Find text in File
grep -H -R vivek /etc/* | cut -d: -f1
grep -rnw '/path/to/somewhere/' -e "pattern"
-h provide the filename
-r or -R is recursive, -n is line number and -w stands match the whole word. -l (letter L) can be added to have just the file name.

Along with these, –exclude or –include parameter could be used for efficient searching. Something like below:

grep –include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"

This will only search through the files which have .c or .h extensions. Similarly a sample use of –exclude:

grep –exclude=*.o -rnw '/path/to/somewhere/' -e "pattern"

Above will exclude searching all the files ending with .o extension. Just like exclude file it's possible to exclude/include directories through –exclude-dir and –include-dir parameter, the following shows how to integrate –exclude-dir:

grep –exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"

Find empty or zero byte file
find /path/to/dest -type f -empty
-delete = to delete the files

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s