Time To Earn

Showing posts with label Delete Empty Lines in UNIX. Show all posts
Showing posts with label Delete Empty Lines in UNIX. Show all posts

Saturday, November 30, 2013

Daily Weapons In Unix for Work -2


To reverse a file using awk and print next three lines after pattern match (Including pattern):

awk '{ a[i++] = $0 } END { for (j=i-1; j>=0;) print a[j--] }' abcd.txt |sed -n '/MANU/{p;n;p;n;p;n;p;}' >abcd_new.txt

(This can be used when you want to print 3 lines before pattern match, including pattern. Logic: reverse a file and print 3 lines after pattern match.)

How to reverse a file using awk:

awk '{ a[i++] = $0 } END { for (j=i-1; j>=0;) print a[j--] }' abcd.txt

How to reverse a file using sed:

sed -n '1!G;h;$p' abcd.txt


how to get yesterday date in unix
YEST=`TZ="GMT+24" date +'%m/%d/%Y'`; echo $YEST


Replace Text : sed -e "s/Old/New/g"

Remove Text : sed -e "s/Text//g"

Remove Text From Front : sed -e "s/^Text//g"

Remove Text From End : 
sed -e "s/Text\$//g"
sed -e 's/Text$//g'

Insert Text in Front : sed -e "s/^/Text/g"

Append Text to End :
sed -e "s/\$/Text/g"
sed -e 's/$/Text/g'

Truncate :
sed -e "s/Text.*//"
cut -c5-8

Downshift and Upshift :
tr '[A-Z]' '[a-z]'
tr '[a-z]' '[A-Z]'

Change Tabs to Spaces : sed -e "s/<tab>/ /g"

Change Multiple Spaces to a Single Space :
sed -e "s/  */ /g"

Change Whitespaces to a Single Space :
sed -e "s/[<tab><space>][<tab><space>]*/<space>/g"

Delete Leading Whitespaces:
sed -e "s/^[<tab><space>]*//g"

Delete Trailing Whitespaces:
sed -e 's/[<tab><space>]*$//g'

Delete Lines:
sed -e "/Text/d" 
grep -v "Text"

Delete Empty Lines:
sed -e '/^*$/d'
sed -e '/^[<tab><space>]*$/d'

Delete First Line:
sed -e '1d'
sed -e '1,7d'

Delete Last Line : sed -e '$d'

Print First Line :
sed -n '1p'
sed -e '2,$d'
sed -e '1q'

Print Last Line :
sed -n '$p'

Delete Comments :
sed -e '/^#/d'
sed -e 's/#.*//'

Delete Text Between Keywords :
sed -e '/Keyword1/,/Keyword2/d'
sed -e '/^Keyword1$/,/^Keyword2$/d'

Extract Text Between Keywords : 
sed -e '/^Keyword1$/,/^Keyword2$/!d'

Print Odd Lines : cat -n file |  sed -e '/.....[02468]/d' -e 's/^.......//'

Print Even Lines : cat -n file |  sed -e '/.....[13579]/d' -e 's/^.......//'

Read a File Backwards : cat -n file | sort -nr | sed 's/^.......//'

Convert < > into LTGT : cat $* | sed -e 's/</\&lt;/g' -e 's/>/\&gt;/g'