How to use the command `ed` (with examples)
- Osx
- December 25, 2023
ed
is the original Unix text editor. It is a line-oriented editor used for creating and modifying text files. Unlike modern editors, ed
does not provide a graphical user interface, but rather operates in a command-line mode.
Use case 1: Start an interactive editor session with an empty document
Code:
ed
Motivation: Starting an interactive editor session with an empty document is useful when you want to create a new file from scratch or when you want to edit an existing file.
Explanation:
ed
: This command starts theed
editor.
Example output:
~
~
~
~
Use case 2: Start an interactive editor session with an empty document and a specific [p]rompt
Code:
ed -p '> '
Motivation: Adding a specific prompt to the interactive editor session can provide a more customizable and interactive experience.
Explanation:
ed
: This command starts theed
editor.-p '> '
: This option sets a specific prompt (in this case, the prompt is “> “).
Example output:
>
Use case 3: Start an interactive editor session with an empty document and without diagnostics, byte counts and ‘!’ prompt
Code:
ed -s
Motivation: In some cases, you may want to suppress the diagnostics, byte counts, and the ‘!’ prompt in the interactive editor session.
Explanation:
ed
: This command starts theed
editor.-s
: This option suppresses the diagnostics, byte counts, and the ‘!’ prompt.
Example output:
~
Use case 4: Edit a specific file (this shows the byte count of the loaded file)
Code:
ed path/to/file
Motivation: Editing a specific file allows you to modify its content directly.
Explanation:
ed
: This command starts theed
editor.path/to/file
: This is the path to the file you want to edit.
Example output:
3
Use case 5: Replace a string with a specific replacement for all lines
Code:
ed path/to/file
,s/regular_expression/replacement/g
Motivation: Replacing a string with a specific replacement can be useful when you want to make bulk changes to the content of a file.
Explanation:
ed
: This command starts theed
editor.path/to/file
: This is the path to the file you want to edit.,s/regular_expression/replacement/g
: This is the command to replace a string with a specific replacement for all lines.,
: Represents all lines.s
: Indicates the substitution command.regular_expression
: Represents the search pattern.replacement
: Represents the replacement string.g
: Stands for global, which replaces all occurrences of the search pattern on each line.
Example output:
3
Conclusion:
The ed
command is a powerful and versatile text editor that can be used for creating, modifying, and replacing text in files. It provides various options and commands to perform different operations. By understanding these use cases and their respective examples, you can effectively use the ed
command to manipulate text files according to your requirements.