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'

No comments: