Gnu sed: Difference between revisions
From wikinotes
(→Usage) |
|||
Line 45: | Line 45: | ||
# Limit scope of 'i' to an address-range | # Limit scope of 'i' to an address-range | ||
# ',' between two addresses selects all lines in between the matches (inclusively) | # ',' between two addresses selects all lines in between the matches (inclusively) | ||
# ( for range between /3/ and /5/, insert newline ) | |||
echo '1\n2\n3\n4\n5\n6' | sed '/3/,/5/i \newline' | echo '1\n2\n3\n4\n5\n6' | sed '/3/,/5/i \newline' | ||
> 1 | > 1 |
Revision as of 14:08, 16 October 2021
Gnu sed performs search/replace within stdin or files.
See also bsd sed.
Documentation
man sed
https://man.archlinux.org/man/core/sed/sed.1.en
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\bat' | sed '/bar/i \newline' > foo > newline > bar > baz > bat # Limit scope of 'i' to an address-range # ',' between two addresses selects all lines in between the matches (inclusively) # ( for range between /3/ and /5/, insert newline ) echo '1\n2\n3\n4\n5\n6' | sed '/3/,/5/i \newline' > 1 > 2 > newline > 3 > newline > 4 > newline > 5 > 6
Usage
Cookbook of really common stuff
# 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