Friday, January 3, 2014

Sed Command Basics


Description: the most command parameter of sed command is 's', which stands for substitute.
Format: sed 'PARAM/REGEXP/REPLACEMENT/FLAG' filename
        It searches for matched patterns (by REGEXP) and replaces it with REPLACEMENT.  PARAM and FLAG decides which match is replaced.

Examples:
  1. Replace every first match in a line 
  $ cat sed_cmd_study.txt
  This is to study sed command in Linux system.
  Actually, this is in a cygwin terminal.
  Here are some list of stuff that I am interested:
  Linux Hacking
  C programming and C++ programming
  Python programming and Perl programming
  Photoshop applications and design
  And all the other related stuffs


  $ sed 's/programming/coding/' sed_cmd_study.txt
  This is to study sed command in Linux system.
  Actually, this is in a cygwin terminal.
  Here are some list of stuff that I am interested:
  Linux Hacking
  C coding and C++ programming

  Python coding and Perl programming
  Photoshop applications and design
  And all the other related stuffs

    [NOTE]: in this case, the original file is not modified


    2.  Replace every matches in file
  $ sed 's/programming/coding/g' sed_cmd_study.txt
  This is to study sed command in Linux system.
  Actually, this is in a cygwin terminal.
  Here are some list of stuff that I am interested:
  Linux Hacking
  C coding and C++ coding
  Python coding and Perl coding
  Photoshop applications and design
  And all the other related stuffs

     
    [NOTE]: in this case, the original file is not modified


     3. Only replace the 2nd occurrence of a line in file
  $ sed 's/programming/coding/2' sed_cmd_study.txt
  This is to study sed command in Linux system.
  Actually, this is in a cygwin terminal.
  Here are some list of stuff that I am interested:
  Linux Hacking
  C programming and C++ coding
  Python programming and Perl coding
  Photoshop applications and design
  And all the other related stuffs

     
    [NOTE]: in this case, the original file is not modified

     4.  Replace all the matches and write the modified lines in a file
  $ sed 's/programming/coding/gw output.txt' sed_cmd_study.txt
  This is to study sed command in Linux system.
  Actually, this is in a cygwin terminal.
  Here are some list of stuff that I am interested:
  Linux Hacking
  C coding and C++ coding
  Python coding and Perl coding
  Photoshop applications and design
  And all the other related stuffs


  $ cat output.txt
  C coding and C++ coding
  Python coding and Perl coding



     5. Delete last X number of characters from each line
  $ sed 's/...$//g' sed_cmd_study.txt
  This is to study sed command in Linux syst
  Actually, this is in a cygwin termin
  Here are some list of stuff that I am interest
  Linux Hack
  C programming and C++ programm
  Python programming and Perl programm
  Photoshop applications and des
  And all the other related stu






No comments: