Friday, May 5, 2017

6 often needed sed scripts for string processing

1. How to remove all empty lines in a file
  sed -e '/^$/d' filename.txt

2. How to remove the leading empty spaces
  (whitespace only) -> sed -e 's/^[ ]*//' /file/path/filename.txt
  (whitespace and tab \t) -> sed -e 's/^[ \t]*//' /file/path/filename.txt

3. How to add some string to starting of all lines of a file
  sed -e 's/^/string-to-add-at-starting/g' /file/path/filename.txt

4. How to add date to starting of all lines
  sed -e "s/^/$(date) /g" /file/path/filename.txt  - Note: The Double quotes.
  Before    ->    line in a file
  After    ->    Thu May  4 17:31:58 IST 2017 line in a file

5. How to add formatted date to starting of all lines
  sed -e "s/^/$(date '+%m\/%d\/%Y %H:%M:%S') /g" /file/path/filename.txt
  Example:
   Before    ->    line in a file
   After    ->    05/04/2017 17:30:50 line in a file

6. How to do multiple replace at one go
  sed -e 's/string-to-find1/string-to-replace1/g' -e 's/string-to-find2/string-to-replace2/g' /file/path/filename.txt

Some More scripts:
7. How to remove all contents after pattern match
  sed -e '/pattern/,$d' /path-to/file/filename.txt
  For Ex: To remove all contents after first empty line -> sed -e '/^$/,$d'


8. How to remove all contents before pattern match
  sed -e '0,/pattern/d' /path-to/file/filename.txt
  For Ex: To remove all contents before first empty line -> sed -e '0,/^$/d'

Wednesday, May 3, 2017

How to create printable version of a man page..?

Most of us are always feel boring to read man pages in terminal window. what if we have a printable version of a particular command's manpage.? Nice isn't it.. so, how we can create a printable version of a manpage...

Step 1: Issue the following command in terminal
$man -t > destination_file_path.ps

Ex:$man -t mkdir > ~/Desktop/mkdir_manpage_printableversion.ps

Now you got a file named " mkdir_manpage_printableversion.ps " in your Desktop :). you can now print and use it..

Note: .ps(Postscript) is the default file type used to print.  It can be opened with any PDF viewer and can be printed.