Gnu sed: Difference between revisions

From wikinotes
(Created page with "Gnu sed performs search/replace within stdin or files.<br> See also bsd sed. = Usage = <blockquote> <source lang="bash"> # Replace 'aaa' with 'bbb' cat echo "aaa_stuff_aa...")
 
Line 1: Line 1:
Gnu sed performs search/replace within stdin or files.<br>
Gnu sed performs search/replace within stdin or files.<br>
See also [[bsd sed]].
See also [[bsd sed]].
= Overview =
<blockquote>
sed lets you manipulate text streams using commands.
* <code>s</code> command search/replaces text (by default on each line)(ex: <code>sed 's/regexp/repl/'</code>)
<syntaxhighlight lang="bash">
</syntaxhighlight>
</blockquote><!-- Overview -->


= Usage =
= Usage =
Line 7: Line 18:
# Replace 'aaa' with 'bbb'
# Replace 'aaa' with 'bbb'
cat echo "aaa_stuff_aaa" \
cat echo "aaa_stuff_aaa" \
| sed 's_aaa_bbb_g'
    | sed 's_aaa_bbb_g'




# Regex  
# Regex
cat echo "aaa_stuff_aaa" \
cat echo "aaa_stuff_aaa" \
| sed 's_[a]*_b_g'
    | sed -E 's_[a]*_b_g'


# Group matching (\2 is a variable that refers to the
# Group matching (\2 is a variable that refers to the
# second match group. In this case, 'stuff'
# second match group. In this case, 'stuff'
cat echo "aaa_stuff_aaa" \
cat echo "aaa_stuff_aaa" \
| sed 's_\([a]*\)\(stuff\)_\2\n'
    | sed -E 's_\([a]*\)\(stuff\)_\2\n'





Revision as of 13:38, 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.

  • s command search/replaces text (by default on each line)(ex: sed 's/regexp/repl/')

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