How to use the sed command in the shell?
In the shell, the sed command is used to process and edit text files line by line. Its basic syntax is as follows:
sed [选项] '动作' 文件名
其中,可以选择以下选项:
- -n: display only lines that have been processed by sed
- Enable multiple sed commands to be applied to input data.
- Modify the input file directly instead of outputting to standard output.
- Support for extended regular expressions.
The possible actions could be:
- Replace all matching strings in the file.
- Delete the matching line.
- Print the lines that match.
- i: Insert text before the specified line.
- a: Append text after the specified line.
To replace all instances of “apple” with “orange” in the file file.txt, you can use the following command:
sed 's/apple/orange/g' file.txt
To directly edit the file file.txt, you can add the -i option.
sed -i 's/apple/orange/g' file.txt