Transform your Text with Sed: The Ultimate Tool for Unix Shell Scripting

Sed (stream editor) is a powerful command-line tool that can be used to perform various text manipulation operations in Unix-like operating systems. Here are a few examples of operations that can be performed using sed:

  1. Search and replace: Sed can be used to search for a specific pattern in a file and replace it with another string. For example, to replace all occurrences of “old” with “new” in a file:
sed 's/old/new/g' file.txt
  1. Delete lines: Sed can be used to delete specific lines in a file. For example, to delete the 2nd line in a file:
sed '2d' file.txt
  1. Insert lines: Sed can be used to insert new lines into a file. For example, to insert a new line after the 2nd line in a file:
sed '2a\New line' file.txt
  1. Extract specific lines: Sed can be used to extract specific lines from a file. For example, to extract lines 2 to 4 from a file:
sed -n '2,4p' file.txt
  1. Remove leading and trailing whitespaces: Sed can be used to remove leading and trailing whitespaces from a file. For example, to remove all leading whitespaces from a file:
sed 's/^[ \t]*//' file.txt
  1. Commenting: Sed can be used to add/remove comments in a file. For example, to remove comments from a file:
sed '/^#/d' file.txt
  1. Translate characters: Sed can be used to translate characters in a file. For example, to translate all uppercase letters to lowercase letters:
sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/' file.txt
  1. Add/increment numbers: Sed can be used to add or increment numbers in a file. For example, to increment all numbers in a file by 1:
sed 's/[0-9]\+/expr & + 1/e' file.txt
  1. Multiple commands: Sed can be used to execute multiple commands in a single command line. For example, to delete the 2nd line, replace all occurrences of “old” with “new”, and add a new line after the 4th line in a file:
sed '2d;s/old/new/g;4a\New line' file.txt
  1. Backup files: Sed can be used to backup a file before making any changes. For example, to backup a file before making any changes:
sed -i.bak 's/old/new/g' file.txt

These are just a few examples of the types of operations that can be performed using sed. Sed is a very powerful tool and can be used to perform a wide range of text manipulation operations. It’s important to note that before making any changes to a file, it’s always a good practice to make a backup copy of the file.