Saturday 30 March 2013

Useful Sed command examples in UNIX

  1. Substitute a regular expression into a new value
  2. A simple example is to change the first occurrence of 'old' on each line from file1 to 'new' and save as file2
    sed 's|old|new|' < file1 > file2
    where 's' is the substitute command, '|' is the delimiter, 'old' is the search pattern in regular expression, and 'new' is the replacement string. We can also test string substitution using 'echo' like this
    echo "old, and some other old stuffs" | sed 's|old|new|'
    which will output 'new, and some other old stuffs'. Note that in this case it only replace the first occurrence of 'old' with 'new'. If we want to replace all 'old' with 'new', we could append a global replacement symbol 'g' after the last delimiter '|'
    echo "old, and some other old stuffs" | sed 's|old|new|g'
    which will output 'new, and some other new stuffs'
  3. Pick any delimiter you like
  4. We were using '|' as the delimiter in the above examples. In fact, we can pick any character as the delimiter, as long as it is not in the string we are looking for. For example,
    echo "old, and some other old stuffs" | sed 's/old/new/g'
    echo "old, and some other old stuffs" | sed 's:old:new:g'
    
    have the same effect.
  5. Use & as the matched string
  6. We could search for a pattern and add some characters on top of the original string like this
    echo "old, and some other old stuffs" | sed 's|[a-z]*|(&)|'
    which will output '(old), and some other old stuffs'. The special character '&' represents the matching pattern. We could have any number of '&' in the replacement string
    echo "old, 123 and 456 some other old stuffs" | sed -r 's|[0-9]+|& &|'
    which will output 'old, 123 123 and 456 some other old stuffs'. Note that we use '-r' here to indicate we are using extended regular expression such that sed will support the use of '+'.

No comments:

Post a Comment