Sed: Difference between revisions
From charlesreid1
No edit summary |
|||
| Line 7: | Line 7: | ||
Sed can be used to edit files in-place using the <code>-i</code> flag. | Sed can be used to edit files in-place using the <code>-i</code> flag. | ||
=Find and Replace= | |||
You can find and replace instances of a string in a file using: | You can find and replace instances of a string in a file using: | ||
| Line 31: | Line 31: | ||
</source> | </source> | ||
=Special/Escape Characters= | |||
{{Main|Regular Expressions}} | {{Main|Regular Expressions}} | ||
| Line 39: | Line 39: | ||
Sometimes you want to look for generic patterns, like "four numbers in a row", rather than something specific, like "5555". This can be done using special/escape characters. | Sometimes you want to look for generic patterns, like "four numbers in a row", rather than something specific, like "5555". This can be done using special/escape characters. | ||
==Numerical Characters== | |||
To match any number between 0 and 9, use <code>[0-9]</code>, like this: | To match any number between 0 and 9, use <code>[0-9]</code>, like this: | ||
| Line 92: | Line 92: | ||
replacement | replacement | ||
</pre> | </pre> | ||
=Sed Commands= | |||
<!-- | |||
<pre> | |||
# | |||
[No addresses allowed.] | |||
The # character begins a comment; the comment continues until the next newline. | |||
If you are concerned about portability, be aware that some implementations of sed (which are not posix conformant) may only support a single one-line comment, and then only when the very first character of the script is a #. | |||
Warning: if the first two characters of the sed script are #n, then the -n (no-autoprint) option is forced. If you want to put a comment in the first line of your script and that comment begins with the letter ‘n’ and you do not want this behavior, then be sure to either use a capital ‘N’, or place at least one space before the ‘n’. | |||
q [exit-code] | |||
This command only accepts a single address. | |||
Exit sed without processing any more commands or input. Note that the current pattern space is printed if auto-print is not disabled with the -n options. The ability to return an exit code from the sed script is a GNU sed extension. | |||
d | |||
Delete the pattern space; immediately start next cycle. | |||
p | |||
Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option. | |||
n | |||
If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If there is no more input then sed exits without processing any more commands. | |||
{ commands } | |||
A group of commands may be enclosed between { and } characters. This is particularly useful when you want a group of commands to be triggered by a single address (or address-range) match. | |||
</pre> | |||
<pre>3.5 The s Command | |||
The syntax of the s (as in substitute) command is ‘s/regexp/replacement/flags’. The / characters may be uniformly replaced by any other single character within any given s command. The / character (or whatever other character is used in its stead) can appear in the regexp or replacement only if it is preceded by a \ character. | |||
The s command is probably the most important in sed and has a lot of different options. Its basic concept is simple: the s command attempts to match the pattern space against the supplied regexp; if the match is successful, then that portion of the pattern space which was matched is replaced with replacement. | |||
The replacement can contain \n (n being a number from 1 to 9, inclusive) references, which refer to the portion of the match which is contained between the nth \( and its matching \). Also, the replacement can contain unescaped & characters which reference the whole matched portion of the pattern space. Finally, as a GNU sed extension, you can include a special sequence made of a backslash and one of the letters L, l, U, u, or E. The meaning is as follows: | |||
\L | |||
Turn the replacement to lowercase until a \U or \E is found, | |||
\l | |||
Turn the next character to lowercase, | |||
\U | |||
Turn the replacement to uppercase until a \L or \E is found, | |||
\u | |||
Turn the next character to uppercase, | |||
\E | |||
Stop case conversion started by \L or \U. | |||
To include a literal \, &, or newline in the final replacement, be sure to precede the desired \, &, or newline in the replacement with a \. | |||
The s command can be followed by zero or more of the following flags: | |||
g | |||
Apply the replacement to all matches to the regexp, not just the first. | |||
number | |||
Only replace the numberth match of the regexp. | |||
Note: the posix standard does not specify what should happen when you mix the g and number modifiers, and currently there is no widely agreed upon meaning across sed implementations. For GNU sed, the interaction is defined to be: ignore matches before the numberth, and then match and replace all matches from the numberth on. | |||
p | |||
If the substitution was made, then print the new pattern space. | |||
Note: when both the p and e options are specified, the relative ordering of the two produces very different results. In general, ep (evaluate then print) is what you want, but operating the other way round can be useful for debugging. For this reason, the current version of GNU sed interprets specially the presence of p options both before and after e, printing the pattern space before and after evaluation, while in general flags for the s command show their effect just once. This behavior, although documented, might change in future versions. | |||
w file-name | |||
If the substitution was made, then write out the result to the named file. As a GNU sed extension, two special values of file-name are supported: /dev/stderr, which writes the result to the standard error, and /dev/stdout, which writes to the standard output.4 | |||
e | |||
This command allows one to pipe input from a shell command into pattern space. If a substitution was made, the command that is found in pattern space is executed and pattern space is replaced with its output. A trailing newline is suppressed; results are undefined if the command to be executed contains a nul character. This is a GNU sed extension. | |||
I | |||
i | |||
The I modifier to regular-expression matching is a GNU extension which makes sed match regexp in a case-insensitive manner. | |||
M | |||
m | |||
The M modifier to regular-expression matching is a GNU sed extension which causes ^ and $ to match respectively (in addition to the normal behavior) the empty string after a newline, and the empty string before a newline. There are special character sequences (\` and \') which always match the beginning or the end of the buffer. M stands for multi-line. | |||
</pre> | |||
<pre> | |||
Though perhaps less frequently used than those in the previous section, some very small yet useful sed scripts can be built with these commands. | |||
y/source-chars/dest-chars/ | |||
(The / characters may be uniformly replaced by any other single character within any given y command.) | |||
Transliterate any characters in the pattern space which match any of the source-chars with the corresponding character in dest-chars. | |||
Instances of the / (or whatever other character is used in its stead), \, or newlines can appear in the source-chars or dest-chars lists, provide that each instance is escaped by a \. The source-chars and dest-chars lists must contain the same number of characters (after de-escaping). | |||
a\ | |||
text | |||
As a GNU extension, this command accepts two addresses. | |||
Queue the lines of text which follow this command (each but the last ending with a \, which are removed from the output) to be output at the end of the current cycle, or when the next input line is read. | |||
Escape sequences in text are processed, so you should use \\ in text to print a single backslash. | |||
As a GNU extension, if between the a and the newline there is other than a whitespace-\ sequence, then the text of this line, starting at the first non-whitespace character after the a, is taken as the first line of the text block. (This enables a simplification in scripting a one-line add.) This extension also works with the i and c commands. | |||
i\ | |||
text | |||
As a GNU extension, this command accepts two addresses. | |||
Immediately output the lines of text which follow this command (each but the last ending with a \, which are removed from the output). | |||
c\ | |||
text | |||
Delete the lines matching the address or address-range, and output the lines of text which follow this command (each but the last ending with a \, which are removed from the output) in place of the last line (or in place of each line, if no addresses were specified). A new cycle is started after this command is done, since the pattern space will have been deleted. | |||
= | |||
As a GNU extension, this command accepts two addresses. | |||
Print out the current input line number (with a trailing newline). | |||
l n | |||
Print the pattern space in an unambiguous form: non-printable characters (and the \ character) are printed in C-style escaped form; long lines are split, with a trailing \ character to indicate the split; the end of each line is marked with a $. | |||
n specifies the desired line-wrap length; a length of 0 (zero) means to never wrap long lines. If omitted, the default as specified on the command line is used. The n parameter is a GNU sed extension. | |||
r filename | |||
As a GNU extension, this command accepts two addresses. | |||
Queue the contents of filename to be read and inserted into the output stream at the end of the current cycle, or when the next input line is read. Note that if filename cannot be read, it is treated as if it were an empty file, without any error indication. | |||
As a GNU sed extension, the special value /dev/stdin is supported for the file name, which reads the contents of the standard input. | |||
w filename | |||
Write the pattern space to filename. As a GNU sed extension, two special values of file-name are supported: /dev/stderr, which writes the result to the standard error, and /dev/stdout, which writes to the standard output.5 | |||
The file will be created (or truncated) before the first input line is read; all w commands (including instances of the w flag on successful s commands) which refer to the same filename are output without closing and reopening the file. | |||
D | |||
If pattern space contains no newline, start a normal new cycle as if the d command was issued. Otherwise, delete text in the pattern space up to the first newline, and restart cycle with the resultant pattern space, without reading a new line of input. | |||
N | |||
Add a newline to the pattern space, then append the next line of input to the pattern space. If there is no more input then sed exits without processing any more commands. | |||
P | |||
Print out the portion of the pattern space up to the first newline. | |||
h | |||
Replace the contents of the hold space with the contents of the pattern space. | |||
H | |||
Append a newline to the contents of the hold space, and then append the contents of the pattern space to that of the hold space. | |||
g | |||
Replace the contents of the pattern space with the contents of the hold space. | |||
G | |||
Append a newline to the contents of the pattern space, and then append the contents of the hold space to that of the pattern space. | |||
x | |||
Exchange the contents of the hold and pattern spaces. | |||
</pre> | |||
--> | |||
==Less Common Commands== | |||
===w command=== | |||
To search for a pattern, and print the resulting pattern to a file, use the <code>w</code> command: | |||
<pre> | |||
$ cat list_file | |||
Phoenix | |||
New York City | |||
San Francisco | |||
Orlando | |||
Atlanta | |||
Seattle | |||
San Antonio | |||
St. Louis | |||
$ sed -n '/San/w search_results' list_file | |||
$ cat search_results | |||
San Francisco | |||
San Antonio | |||
</pre> | |||
===e command=== | |||
To output the results of a command into a new line, the <code>e</code> command can be used. For example, the contents of a small file (called small_file in this example) could be inserted into a line of the file test_file: | |||
<pre> | |||
$ cat new_item | |||
Boston | |||
$ sed '/New York/e cat new_item' list_file | |||
Phoenix | |||
Boston | |||
New York City | |||
San Francisco | |||
Orlando | |||
Atlanta | |||
Seattle | |||
San Antonio | |||
St. Louis | |||
</pre> | |||
The new line, created from the output of the command <code>cat new_item</code>, is inserted in a new line, above the line matching the search pattern. | |||
Revision as of 15:43, 4 May 2011
Sed is a *nix system utility that will come with 99% of *nix systems. It's an in-place string manipulation program that can come in handy to make a whole lot of typing into a few lines of string manipulation. It's ugly, but once you start to use it you'll wonder how you ever lived without it.
Sed introduction and tutorial: http://www.grymoire.com/Unix/Sed.html
Editing Files In-Place
Sed can be used to edit files in-place using the -i flag.
Find and Replace
You can find and replace instances of a string in a file using:
$ sed -i -e 's/peanut butter/jelly/g' file{1,2,3}.txt
This replaces peanut butter with jelly in file1.txt, file2,txt, and file3.txt. To replace more than one thing, use
$ sed -i -e 's/peanut butter/jelly/g' \
-e 's/green eggs/ham/g' \
-e 's/water/wine/g' \
file{1,2,3}.txt
or, more succinctly:
$ sed -i -e 's/peanut butter/jelly/g;s/green eggs/ham/g' \
file{1,2,3}.txt
Special/Escape Characters
NOTE: This section is specific to GNU sed, other versions of sed will likely behave differently.
Sometimes you want to look for generic patterns, like "four numbers in a row", rather than something specific, like "5555". This can be done using special/escape characters.
Numerical Characters
To match any number between 0 and 9, use [0-9], like this:
$ echo "5" | sed -e 's/[0-9]/replacement/' replacement
To match a pattern of N numbers between 0 and 9, use \{N\}, like this:
$ echo "5678" | sed -e 's/[0-9]\{4\}/replacement/'
replacement
If you want to match a pattern of numbers between 0 and 9, and know there will be somewhere between M and N numbers, you can use the syntax \{M,N\}. For example, if you want to replace a number between 2 and 4 digits long:
$ echo "56" | sed -e 's/[0-9]\{2,4\}/replacement/'
replacement
$ echo "5234678" | sed -e 's/[0-9]\{2,4\}/replacement/'
replacement678
$ echo "5" | sed -e 's/[0-9]\{2,4\}/replacement/'
5
Note that in the last command executed, the replacement pattern doesn't show up because the largest pattern of numbers between 0 and 9 is 1, which does not fall in the range of 2 to 4.
Since \{M,N\} is ugly and burdensome to type, you can use the sed flag -r or --regexp-extended to eliminate the need for backslashes:
$ echo "5234678" | sed -e 's/[0-9]\{2,4\}/replacement/'
replacement678
$ echo "5234678" | sed -re 's/[0-9]{2,4}/replacement/'
replacement678
To leave the upper bound of the number size unspecified, use \{N,\}:
$ echo "52" | sed -re 's/[0-9]{2,}/replacement/'
replacement
$ echo "5234678" | sed -re 's/[0-9]{2,}/replacement/'
replacement
$ echo "5223902949082309448792387234" | sed -re 's/[0-9]{2,}/replacement/'
replacement
Sed Commands
Less Common Commands
w command
To search for a pattern, and print the resulting pattern to a file, use the w command:
$ cat list_file Phoenix New York City San Francisco Orlando Atlanta Seattle San Antonio St. Louis $ sed -n '/San/w search_results' list_file $ cat search_results San Francisco San Antonio
e command
To output the results of a command into a new line, the e command can be used. For example, the contents of a small file (called small_file in this example) could be inserted into a line of the file test_file:
$ cat new_item Boston $ sed '/New York/e cat new_item' list_file Phoenix Boston New York City San Francisco Orlando Atlanta Seattle San Antonio St. Louis
The new line, created from the output of the command cat new_item, is inserted in a new line, above the line matching the search pattern.
References
- This page has more information on special/escape characters: http://sed.sourceforge.net/sedfaq6.html
- One-line sed commands: http://sed.sourceforge.net/grabbag/tutorials/sed1line.txt