The Linux Newbie Guide  ⇒    Fundamentals     Advanced     Supplement   Command Index   ENG⇒中
All rights reserved, please indicate the source when citing
 

 sed

1.0 Introduction to sed
1.1 File String Modification with sed
        Basic Usage of sed
        Advanced Usage of sed
            delimiter
            ADDRESS Range
            OPTION
            FLAG
            Flow Control
            COMMAND

ENG⇒中ENG⇒中
  1.0 Introduction to sed

sed and awk are two powerful tools that are often compared because of their similar strength and excellent support for regular expressions. They each have their own scripting languages, with sed mainly used for automated text file modification, while awk can be imagined as a lightweight interpreted language similar to C, commonly used for general purposes, statistics, and reformatting output.

In Chinese books or websites, the explanations for sed and awk are often limited to simple applications and can be ambiguous. Moreover, much of the content is repetitive, making it difficult for users who want to delve deeper to find more detailed information. Don't be too naive to think that you can rely solely on the man pages; man pages are meant for reference by people already familiar with the subject. Trying to learn sed and awk solely from man pages is like trying to learn conversational English from a dictionary. Therefore, this attempt aims to document all the functionalities and potentials of sed and awk. If you are a casual user and don't want to waste too much time, referring to the basic usage of sed and awk should be sufficient for more than 90% of your needs.




^ back on top ^


1.1 File String Modification with sed

While grep can utilize powerful regular expressions to search for strings in files, it lacks the ability to perform editing actions such as deletion, replacement, or insertion on the matched strings. This is where sed comes in to complement grep's editing functionality. Moreover, sed's programmable features are often used to automate text file modifications.

Although vi (or any text editor) can also be used to search for and modify file contents, manually opening files, making changes, and then saving them can be time-consuming. However, if you are familiar with sed operations, all of these tasks can be automated. For example, when a company relocates, there might be numerous spreadsheet files with the old company address, and by making good use of sed, you can efficiently and automatically update all the files with the new address.

The usage of sed may seem a bit abstract, so let's explain the basic usage and each parameter separately.



Basic Usage of sed
Like other powerful commands, the functionality of sed becomes more powerful as its syntax becomes more complex and abstract. However, it's a valuable tool to learn, especially for automating text file modifications.

The basic usage of sed is as follows: sed [-OPTION] [ADD1][,ADD2] [COMMAND] [/PATTERN][/REPLACEMENT]/[FLAG] [FILE].

To make it easier to understand, let's first provide an example, as an example explains a thousand words.

For instance, if we want to change occurrences of "The" or "the" to uppercase "THE" in lines 1 to 8 of the file "MyFile.txt," we can use the following command:

sed  -e '1,8 s/ [Tt]he/ THE/ g' MyFile.txt   
   
    OPTION  ADD  COMMAND  PATTERN  REPLACE  FLAG  FILE

Since each parameter can be complex and abstract, sed may sometimes interpret them incorrectly. As a general rule, except for the file and option parameters, all other parameters should be enclosed in single quotes (').

In the example above, if the address field is omitted, it represents all text. The "-e" option is the default and can be omitted in common usage, so if no options are added, sed will execute with the default "-e" option (indicating script interpret).

The most basic command in sed is the search and replace command "s," and its basic syntax is "s/PATTERN/REPLACEMENT/". It works similarly to the vi replace command. The pattern can be a valid regular expression or a simple string.

If you want to search and replace a word, you can add a space before the pattern and the replacement string (since words are separated by spaces). For example, if there's a sentence "This is a book," and you want to make the word "is" uppercase, you can use this method. However, be cautious if the word "This" contains the substring "is," as the output might become "ThIS IS a book." In such cases, using a regular expression with Match the single word might be a better solution if you are familiar with regular expressions.

Examples:
$ echo 'This is a book' | sed 's/is/IS/g' ← Replace "is" with "IS" (no space before the word)
ThIS IS a book
$ echo 'This is a book' | sed 's/ is/ IS/g' ←dd a space before the pattern and replacement
This IS a book
$ echo 'This is a book' | sed 's/\<is\>/IS/g' ←Use a regular expression with word boundaries
This IS a book
$ sed 's/\<is\>/IS/g' fileA ←Replace "is" with "IS" in the file "fileA"
$ sed 's/\<is\>/IS/g' fileA fileB fileC ←Process multiple files at once

The sed FLAG "g" stands for global replacement, which means it replaces all occurrences in a line. Without this flag, sed will only replace the first occurrence and then move on to the next line.

As sed stands for "Stream EDitor," the changes made in the above examples are only output to the screen and do not modify the original files. To save the changes to a file, you need to redirect the output to a file using the../pipe/pipe.html#redirection operator. for Example sed 's/can/CAN/' INPUT_FILE > SAVE_FILE.

E.g.:
$ echo 'this is a apple' | sed 's/a/AN/' ←Replace "a" with "AN" (only replaces the first occurrence)
this is AN apple
$ echo 'this is a apple' | sed 's/a/AN/g' ←Add the "g" flag for global replacement (replaces all occurrences)
this is AN ANpple
$ echo 'this is a apple' | sed 's/ is//g' ←Delete the word "is" (replace with an empty string)
this a apple
$ cat my_file.txt | sed '4,5 s/Google/Yahoo/g' > new.txt ←Replace "Google" with "Yahoo" in lines 4 to 5 of the file "my_file.txt" and save as "new.txt"
$ sed '4,5 s/Google/Yahoo/g' < my_file.txt > new.txt ←Same functionality as above

If you want to search and replace multiple patterns, you can use the "-e" option or a pipeline to process multiple sed commands.

Example:
$ echo 'this is a apple' | sed 's/a/an/' | sed 's/apple/APPLE/'← Replace "a" with "an" and "apple" with "APPLE"
this is an APPLE
$ echo 'this is a apple' | sed -e 's/a/an/' -e 's/apple/APPLE/' ← Same functionality as above




^ back on top ^


  Advanced Usage of sed



^ back on top ^




   [note]

That's great to know! The GNU sed official website and Bruce Barnett's tutorial are indeed excellent resources for learning more about sed and exploring useful sed program examples. These resources can provide a deeper understanding of sed's capabilities and how to use it effectively for text manipulation and editing tasks.

For those interested in delving further into sed, the following resources can be valuable references:

  1. GNU sed Official Website (sed, a stream editor Examples):

  2. Bruce Barnett's "Sed - An Introduction and Tutorial":