Sunday, 15 December 2024

Sed command

 

The sed command in Unix is a stream editor used for performing basic text transformations on an input stream (a file or input from a pipeline). It is often used for tasks such as search and replace, deleting lines, inserting lines, and more.

Syntax of sed command

sed [options] 'command' file
  • command: The operation to perform on the input text.
  • file: The file on which sed will operate. If no file is specified, sed reads from standard input (stdin).
  • options: Optional flags that modify sed's behavior.

Common sed Commands and Usage:

1. Search and Replace

The most common use of sed is for search and replace. It uses the syntax:

sed 's/old_text/new_text/' file
  • s/old_text/new_text/: This command searches for old_text and replaces it with new_text.

Example:


sed 's/apple/orange/' fruits.txt

This will replace the first occurrence of the word "apple" with "orange" in each line of fruits.txt


2 .Global Replacement

To replace all occurrences of a pattern in a line, use the g flag:



sed 's/old_text/new_text/g' file

Example:

sed 's/apple/orange/g' fruits.txt
  • This will replace all occurrences of "apple" with "orange" in each line of fruits.txt

No comments:

Post a Comment