Gnu sed: Difference between revisions
From wikinotes
Line 4: | Line 4: | ||
= Overview = | = Overview = | ||
<blockquote> | <blockquote> | ||
sed lets you manipulate text streams using commands. | sed lets you manipulate text streams using '''commands'''. | ||
example commands: | example commands: | ||
<syntaxhighlight lang="bash"> | |||
# 's' command search/replaces text | |||
echo 'foo_bar_baz' | sed 's/bar/BAR/g' | |||
> 'foo_BAR_gaz' | |||
# 'i'/'a' commands prepend/append newlines to each line | |||
echo 'foo\nbar\nbaz' | sed 'i \my newline' | |||
> my newline | |||
> foo | |||
> my newline | |||
> bar | |||
> my newline | |||
> baz | |||
</syntaxhighlight> | |||
By default, all commands operate on every line.<br> | |||
You can use '''addresses''' to limit the scope of a command. | |||
<syntaxhighlight lang="bash"> | <syntaxhighlight lang="bash"> | ||
# Limit scope of 'i' command to lines matching /bar/ | |||
echo 'foo\nbar\nbaz' | sed '/bar/i \my newline' | |||
> foo | |||
> my newline | |||
> bar | |||
> baz | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Overview --> | </blockquote><!-- Overview --> |
Revision as of 13:50, 16 October 2021
Gnu sed performs search/replace within stdin or files.
See also bsd sed.
Overview
sed lets you manipulate text streams using commands.
example commands:
# 's' command search/replaces text echo 'foo_bar_baz' | sed 's/bar/BAR/g' > 'foo_BAR_gaz' # 'i'/'a' commands prepend/append newlines to each line echo 'foo\nbar\nbaz' | sed 'i \my newline' > my newline > foo > my newline > bar > my newline > bazBy default, all commands operate on every line.
You can use addresses to limit the scope of a command.# Limit scope of 'i' command to lines matching /bar/ echo 'foo\nbar\nbaz' | sed '/bar/i \my newline' > foo > my newline > bar > baz
Usage
# Replace 'aaa' with 'bbb' cat echo "aaa_stuff_aaa" \ | sed 's_aaa_bbb_g' # Regex cat echo "aaa_stuff_aaa" \ | sed -E 's_[a]*_b_g' # Group matching (\2 is a variable that refers to the # second match group. In this case, 'stuff' cat echo "aaa_stuff_aaa" \ | sed -E 's_\([a]*\)\(stuff\)_\2\n' # Replace file contents sed -i"bak" "s_aaa_bbb_g" /path/to/file