📜  sed 行 - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:34:54.190000             🧑  作者: Mango

Sed - Stream Editor

Sed (stream editor) is a Unix command line utility that is used to perform text transformations. It reads text from a file or standard input stream, performs various operations on it according to your script, and then outputs the modified text to standard output stream.

Sed is commonly used for simple substitutions and find-and-replace operations, as well as more complex text transformations. It is often used in combination with other Unix utilities such as grep and awk.

Basic Syntax

The basic syntax for sed commands is as follows:

sed 'command' input_file
  • The command is a set of instructions that tells sed what to do with the text.
  • The input_file is the file from which sed reads text. If no input file is specified, sed reads from standard input.
Examples
Replace a string

The following command replaces all occurrences of "foo" with "bar" in the input file:

sed 's/foo/bar/g' input.txt

In this command, s indicates a substitution command, foo is the pattern to replace, bar is the replacement text, and g means “global” (replace all occurrences).

Delete lines

The following command deletes all lines that contain the string "foo":

sed '/foo/d' input.txt

In this command, /foo/ is a regular expression that matches any line containing "foo", and d is the delete command.

Append and insert lines

The following command appends a line with "This is a new line" at the end of the file:

sed '$a\
This is a new line' input.txt

In this command, $ matches the last line, a is the append command, and \ is used to indicate a new line.

The following command inserts a line with "This is a new line" before the first line:

sed '1i\
This is a new line' input.txt

In this command, 1 matches the first line, i is the insert command.

Conclusion

Sed is a powerful and flexible tool for manipulating text on the command line. It can perform simple and complex text transformations, and can be used in combination with other Unix utilities. With a good understanding of its syntax and commands, sed can save you a lot of time and effort in processing text files.