Mastering SED in Linux Scripting

What is Sed?

Sed is a text stream editor that performs basic text transformations on an input stream (a file or input from a pipeline) based on a set of specified commands. It’s particularly useful for tasks like find-and-replace operations, text substitution, line deletion or insertion, and more.

 
 
 
Basic Syntax

The basic structure of a Sed command is as follows:

sed ‘expression’ file

 

Expression:  The action or set of commands you want to perform on the input.
File:  The input file on which Sed should operate. If not specified, Sed reads from standard input.

 

 
 
Sed Examples

1. Find and Replace:

Let’s say you have a text file named `document.txt`, and you want to replace all occurrences of “old” with “new”.

sed ‘s/old/new/g’ document.txt

 

2. Delete Lines:

Suppose you want to remove lines containing a specific keyword, such as “obsolete”.

sed ‘/obsolete/d’ document.txt

 

3. Numbering Lines:

You can use Sed to add line numbers to a file.

sed = document.txt | sed ‘N;s/\n/\t/’

 

4. Appending and Inserting Lines:

Adding content at the beginning or end of a file can be achieved with Sed.

sed ‘1i This is the first line’ document.txt
sed ‘$a This is the last line’ document.txt

 

 
 
Automation with Sed: Script Example

Here’s a simple script named `process_logs.sh` that uses Sed to extract IP addresses from a log file:

#!/bin/bash

log_file=”access.log”

sed -nE ‘s/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+).*/\1/p’ $log_file

 

Make the script executable (`chmod +x process_logs.sh`), and running it will extract and print IP addresses from the `access.log` file.

 

 

You may also like:

https://hackedyou.org/advanced-linux-shell-scripting/

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top