Home > Text Processing & Search > ex

ex: Line-Oriented Text Editor

ex is the line-oriented mode of the Vi IMproved (Vim) editor, primarily used for scripting and automated text processing. It offers powerful features for editing specific lines in a file or batch modifying multiple files, making it more suitable for non-interactive scripting than interactive use.

Overview

ex is the line-based command mode of the Vi editor. It is very useful for processing file content line by line or performing complex text transformations using regular expressions. It is particularly useful as a powerful tool for automatically modifying files within shell scripts.

Key Features

  • Line-based text editing
  • Optimized for scripting and automated tasks
  • Powerful regular expression support
  • Uses the same command set as Vi/Vim
  • Supports non-interactive mode

Key Options

ex primarily executes commands directly within a file, but it offers a few command-line options to control specific behaviors upon startup.

Startup and Mode Options

Generated command:

Try combining the commands.

Description:

`ex` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

ex is primarily used to perform specific tasks within scripts or when switching to the `:ex` command within the vi editor.

Open File and Print Content

ex -s file.txt <<EOF
%p
q!
EOF

Opens a file in ex mode, prints all lines, and then exits.

Substitute String in File and Save

ex -s -c '%s/old_string/new_string/g | wq' file.txt

Substitutes all occurrences of 'old_string' with 'new_string' in file.txt, then saves and exits.

Batch Substitute String in Multiple Files

for f in *.txt; do ex -s -c '%s/error/warning/g | wq' "$f"; done

Substitutes 'error' with 'warning' in all .txt files in the current directory.

Delete Specific Line

ex -s -c '5d | wq' file.txt

Deletes the 5th line of file.txt and saves the changes.

Tips & Precautions

ex is more suited for scripting or automated tasks than interactive use, and it's beneficial to know a few tips for efficient text processing.

Key Tips

  • In non-interactive scripts, always use the `-s` (silent) option to suppress unnecessary messages.
  • Commands are the same as in vi's command mode; use `:wq` to save and exit, and `:q!` to exit without saving.
  • Regular expressions can be used powerfully, similar to `sed`. `%s/pattern/replacement/g` is used to substitute patterns throughout the entire file.
  • ex is part of the `vi` or `vim` package, which is installed by default on most Linux systems.
  • You can chain multiple ex commands on a single line using the pipe symbol (`|`).

Same category commands