Unix Command Reading Each New Line in Text File to Run in C Program Without Scripting

Linux sed command

Updated: 11/06/2021 by Computer Hope

sed command

On Unix-like operating systems, sed is a stream editor: information technology filters and transforms text.

This page covers the GNU/Linux version of sed.

Description

The sed stream editor performs basic text transformations on an input stream (a file, or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such equally ed), sed works past making only one laissez passer over the input(s), and is consequently more than efficient. Simply it is sed'south ability to filter text in a pipeline which particularly distinguishes it from other types of editors.

Syntax

sed          OPTIONS... [SCRIPT] [INPUTFILE...]

If you lot do not specify INPUTFILE, or if INPUTFILE is "-", sed filters the contents of the standard input. The script is actually the outset non-option parameter, which sed specially considers a script and non an input file if and but if none of the other options specifies a script to be executed (that is, if neither of the -e and -f options is specified).

Options

-n, --quiet, --silent Suppress automatic printing of design space.
-e script,
--expression= script
Add the script script to the commands to be executed.
-f script-file,
--file= script-file
Add together the contents of script-file to the commands to be executed.
--follow-symlinks Follow symlinks when processing in place.
-i[SUFFIX],
--in-place[= SUFFIX]
Edit files in place (this makes a fill-in with file extension SUFFIX, if SUFFIX is supplied).
-l Due north, --line-length= N Specify the desired line-wrap length, N, for the "fifty" command.
--POSIX Disable all GNU extensions.
-r, --regexp-extended Employ extended regular expressions in the script.
-s, --separate Consider files equally separate rather than as a single continuous long stream.
-u, --unbuffered Load minimal amounts of data from the input files and flush the output buffers more ofttimes.
--help Display a assist bulletin, and go out.
--version Output version information, and exit.

Sed programs

A sed program consists of one or more sed commands, passed in by 1 or more of the -e, -f, --expression, and --file options, or the first not-option argument if none of these options are used. This documentation frequently refers to "the" sed script; this should be understood to mean the in-guild catenation of all of the scripts and script-files passed in.

Commands within a script or script-file can exist separated by semicolons (";") or newlines (ASCII lawmaking x). Some commands, due to their syntax, cannot be followed by semicolons working as control separators and thus should be terminated with newlines or exist placed at the stop of a script or script-file. Commands tin can likewise be preceded with optional non-significant whitespace characters.

Each sed control consists of an optional address or accost range (for instance, line numbers specifying what part of the file to operate on; see selecting lines for details), followed by a 1-character command name and any additional command-specific code.

How sed works

sed maintains two data buffers: the active blueprint space, and the auxiliary hold space. Both are initially empty.

sed operates by performing the following cycle on each line of input: kickoff, sed reads one line from the input stream, removes any abaft newline, and places it in the pattern infinite. Then commands are executed; each control tin can have an address associated to it: addresses are a kind of condition code, and a command is only executed if the condition is verified before the command is to exist executed.

When the cease of the script is reached, unless the -northward option is in utilise, the contents of pattern space are printed out to the output stream, calculation back the trailing newline if information technology was removed. Then the next wheel starts for the next input line.

Unless special commands (like 'D') are used, the design space is deleted between ii cycles. The concord space, on the other hand, keeps its information between cycles (see commands 'h', 'H', 'x', 'g', 'G' to motion data betwixt both buffers).

Selecting lines with sed

Addresses in a sed script can be in whatsoever of the following forms:

number Specifying a line number volition match only that line in the input. (Note that sed counts lines continuously across all input files unless -i or -southward options are specified.)
starting time ~ pace This GNU extension of sed matches every step lines starting with line starting time. In particular, lines volition exist selected when there exists a non-negative n such that the current line-number equals first + (n * step). Thus, to select the odd-numbered lines, ane would use ane~2; to pick every tertiary line starting with the second, 'ii~three' would exist used; to choice every fifth line starting with the tenth, use '10~5'; and 'fifty~0' is another way of maxim l.
$ This address matches the final line of the terminal file of input, or the last line of each file when the -i or -s options are specified.
/ regexp / This selects any line which matches the regular expression regexp. If regexp itself includes any "/" characters, each must exist escaped by a backslash ("\").

The empty regular expression '//' repeats the last regular expression match (the aforementioned holds if the empty regular expression is passed to the s control). Note that modifiers to regular expressions are evaluated when the regular expression is compiled, thus it is invalid to specify them together with the empty regular expression.

\ % regexp % (The % may exist replaced by whatever other single character.)

This also matches the regular expression regexp, but allows one to use a different delimiter than "/". This option is particularly useful if the regexp itself contains a lot of slashes, since it avoids the tedious escaping of every "/". If regexp itself includes any delimiter characters, each must exist escaped by a backslash ("\").

/ regexp /I

\ % regexp % I

The I modifier to regular-expression matching is a GNU extension which causes the regexp to be matched in a case-insensitive (as opposed to case-sensitive) manner.
/ regexp /M

\ % regexp % M

The Chiliad modifier to regular-expression matching is a GNU sed extension which causes ^ and $ to match respectively (in improver to the normal behavior) the empty string afterward a newline, and the empty string earlier a newline. There are special character sequences ("\`" and "\'") which always match the beginning or the terminate of the buffer. One thousand stands for multi-line.

If no addresses are given, then all lines are matched; if one address is given, then just lines matching that address are matched.

An address range tin can be specified by specifying two addresses separated by a comma (","). An address range matches lines starting from where the first address matches, and continues until the second accost matches (inclusively).

If the second accost is a regexp, then checking for the ending lucifer starts with the line following the line which matched the first address: a range e'er spans at least two lines (except of class if the input stream ends).

If the second address is a number less than (or equal to) the line matching the first address, then only the one line is matched.

GNU sed as well supports some special two-address forms; all these are GNU extensions:

0,/ regexp / A line number of 0 can be used in an address specification like 0,/ regexp / so that sed volition attempt to friction match regexp in the beginning input line too. In other words, 0,/ regexp / is similar to 1,/ regexp /, except that if addr2 matches the very kickoff line of input the 0,/ regexp / form will consider information technology to end the range, whereas the 1,/ regexp / class will friction match the beginning of its range and hence make the range span up to the 2nd occurrence of the regular expression.

Note that this is the only identify where the 0 accost makes sense; at that place is no "0th" line, and commands that are given the 0 address in any other fashion gives an error.

addr1 ,+ Northward Matches addr1 and the Northward lines following addr1.
addr1 ,~ Northward Matches addr1 and the lines following addr1 until the adjacent line whose input line number is a multiple of Due north.

Appending the ! character to the end of an address specification negates the sense of the lucifer. That is, if the ! character follows an address range, then only lines which exercise not match the address range will be selected. This also works for singleton addresses, and, possibly perversely, for the null accost.

Overview of regular expression syntax

To know how to use sed, sympathize regular expressions ("regexp" for brusk). A regular expression is a pattern that is matched against a subject area string from left to correct. Nearly characters are ordinary: they stand for themselves in a blueprint, and match the respective characters in the subject. Equally a simple example, the pattern

The quick brown fox

...matches a portion of a subject string that is identical to itself. The ability of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the design by the use of special characters, which do not stand up for themselves but instead are interpreted in some special way. Here is a brief description of regular expression syntax as used in sed:

char A unmarried ordinary character matches itself.
* Matches a sequence of nix or more instances of matches for the preceding regular expression, which must be an ordinary character, a special graphic symbol preceded past "\", a ".", a grouped regexp (see below), or a bracket expression. As a GNU extension, a postfixed regular expression can also be followed by "*"; for case, a** is equivalent to a*. POSIX 1003.ane-2001 says that * stands for itself when it appears at the beginning of a regular expression or subexpression, just many not-GNU implementations exercise non back up this, and portable scripts should instead apply "\*" in these contexts.
\+ Similar *, but matches one or more. It is a GNU extension.
\? Like *, but only matches zippo or one. Information technology is a GNU extension.
\{ i \} Similar *, but matches exactly i sequences (i is a decimal integer; for compatibility, go on information technology between 0 and 255, inclusive).
\{ i , j \} Matches betwixt i and j, inclusive, sequences.
\{ i ,\} Matches more than or equal to i sequences.
\( regexp \) Groups the inner regexp as a whole; this is used to:
  • Apply postfix operators, like \(abcd\)*: this searches for zero or more than whole sequences of 'abcd', while abcd* would search for 'abc' followed by zero or more occurrences of 'd'. Note that support for \(abcd\)* is required by POSIX 1003.1-2001, but many non-GNU implementations do not back up it and hence it is non universally portable.
  • Employ back references (see below).
. Matches any grapheme, including a newline.
^ Matches the zilch string at beginning of the pattern space, i.e., what appears after the ^ must appear at the start of the pattern space.

In most scripts, pattern infinite is initialized to the content of each line. So, information technology is a useful simplification to remember of ^#include as matching only lines where '#include' is the first thing on line—if there are spaces before, for example, the match fails. This simplification is valid as long as the original content of design infinite is not modified, for instance with an due south command.

^ acts equally a special character only at the beginning of the regular expression or subexpression (that is, after \( or \|). Portable scripts should avoid ^ at the beginning of a subexpression, though, as POSIX allows implementations that treat ^ every bit an ordinary graphic symbol in that context.

$ It is the same as ^, merely refers to terminate of design space. $ also acts as a special graphic symbol only at the terminate of the regular expression or subexpression (that is, before \) or \|), and its use at the end of a subexpression is not portable.
[ listing ]

[^ listing ]

Matches any single graphic symbol in list: for example, [aeiou] matches all vowels. A list may include sequences like char1 - char2, which matches whatsoever character between char1 and char2. For example, [b-e] matches whatsoever of the characters b, c, d, or e.

A leading ^ reverses the pregnant of list, so that it matches any single character not in listing. To include ] in the listing, make information technology the first character (subsequently the ^ if needed); to include - in the list, brand it the get-go or final; to include ^ put it afterward the showtime grapheme.

The characters $, *, ., [, and \ are usually not special inside listing. For example, [\*] matches either '\' or '*', because the \ is not special here. However, strings similar [.ch.], [=a=], and [:space:] are special within list and correspond collating symbols, equivalence classes, and character classes, respectively, and [ is therefore special inside listing when it is followed by ., =, or :. Also, when not in POSIXLY_CORRECT mode, special escapes similar \n and \t are recognized within listing. See escapes for more information.

regexp1 \| regexp2 Matches either regexp1 or regexp2. Use parentheses to utilise complex culling regular expressions. The matching procedure tries each culling in plough, from left to right, and the outset i that succeeds is used. This selection is a GNU extension.
regexp1regexp2 Matches the concatenation of regexp1 and regexp2. Concatenation binds more tightly than \|, ^, and $, but less tightly than the other regular expression operators.
\ digit Matches the digit-th \(...\) parenthesized subexpression in the regular expression. This option is called a back reference. Subexpressions are implicitly numbered by counting occurrences of \( left-to-correct.
\n Matches the newline character.
\ char Matches char, where char is ane of $, *, ., [, \, or ^. Note that the only C-similar backslash sequences that y'all tin can portably presume to be interpreted are \northward and \\; in particular \t is not portable, and matches a 't' nether about implementations of sed, rather than a tab graphic symbol.

Notation that the regular expression matcher is greedy, i.e., matches are attempted from left to right and, if two or more matches are possible starting at the same character, it selects the longest.

For example:

abcdef Matches "abcdef".
a*b Matches nil or more "a" characters, followed past a unmarried "b". For instance, "b" or "aaaaaaab".
a\?b Matches "b" or "ab".
a\+b\+ Matches one or more than "a" characters followed past 1 or more "b"s. "ab" is the shortest possible lucifer, but other examples are "aaaaab", "abbbbbb", or "aaaaaabbbbbbb".
.* or .\+ Either of these expressions volition lucifer all of the characters in a non-empty string, merely simply .* volition match the empty string.
^principal.*(.*) This matches a cord starting with "main", followed past an opening and closing parenthesis. The "northward", "(" and ")" need non be adjacent.
^# This matches a cord commencement with "#".
\\$ This matches a string catastrophe with a unmarried backslash. The regexp contains two backslashes for escaping.
\$ This matches a string consisting of a unmarried dollar sign.
[a-zA-Z0-9] In the C locale, this matches any ASCII messages or digits.
[^ tab ]\+ (Hither tab stands for a single tab character.) This matches a string of one or more characters that does not incorporate a space or a tab. Unremarkably this means a give-and-take.
^\(.*\)\n\i$ This matches a cord consisting of two equal substrings separated past a newline.
.\{9\}A$ This matches nine characters followed by an 'A'.
^.\{15\}A This matches the start of a string that contains 16 characters with the last character of being 'A'.

Often-used commands

If you utilise sed at all, you will probably want to know these commands.

# (No addresses immune with this command.) The # character begins a comment; the comment continues until the adjacent newline.

If you are concerned about portability, be aware that some implementations of sed (which are not POSIX conformant) may just support a single one-line comment, and so merely when the very outset character of the script is a #.

Warning: if the outset 2 characters of the sed script are #n, and so 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 lot do not want this beliefs, then either employ a upper-case letter 'North', or place at least 1 infinite before the 'n'.

q [exit-code] This command only accepts a single address.

Get out sed without processing any more commands or input. Note that the electric current pattern infinite 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 commencement side by side cycle.
p Impress out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line selection.
north If car-print is not disabled, print the pattern space, so, regardless, supervene upon the pattern space with the next line of input. If there is no more input and then sed exits without processing any more commands.
{ commands } A group of commands may be enclosed betwixt { and } characters. This option is specially useful when you want a group of commands to exist triggered by a single address (or accost-range) match.

The s command

The syntax of the south command (which stands for "substitute") is: 's/ regexp / replacement / flags'. The / characters may be uniformly replaced by any other single graphic symbol within any given due south control. The / graphic symbol (or whatever other character is used in its stead) can announced in the regexp or replacement only if it'due south preceded by a \ character.

The s command is probably the most important in sed and has a lot of dissimilar options. Its basic concept is simple: the s command attempts to match the design space confronting the supplied regexp; if the friction match is successful, so that portion of the blueprint space which was matched is replaced with replacement.

The replacement tin can comprise \ northward (n being a number from 1 to 9, inclusive) references, which refer to the portion of the lucifer that is contained between the nthursday \( and its matching \). As well, the replacement can contain unescaped & characters which reference the whole matched portion of the design infinite. Finally, as a GNU sed extension, you tin include a special sequence made of a backslash and one of the messages L, 50, U, u, or E. The meaning is as follows:

\50 Turn the replacement to lowercase until a \U or \Eastward is constitute
\l Turn the side by side character to lowercase
\U Plow the replacement to uppercase until a \Fifty or \E is found
\u Plow the next character to capital
\East Terminate instance conversion started by \50 or \U

To include a literal \, &, or newline in the final replacement, precede the desired \, &, or newline in the replacement with a \.

The s control can be followed by naught or more than of the following flags:

g Employ the replacement to all matches to the regexp.
number Simply supercede the number 'th match of the regexp.

Notation: the POSIX standard does not specify what should happen when you mix the m 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 numberthursday on.

p If the substitution was fabricated, so print the new pattern space.

Annotation: when both the p and due east options are specified, the relative ordering of the two produces very different results. In general, ep (evaluate and then print) is what y'all desire, just 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 eastward, printing the pattern infinite earlier and after evaluation, while in general flags for the s command show their effect once. This behavior, although documented, might modify in future versions.

due west file If the substitution was fabricated, then write out the outcome to the named file. As a GNU sed extension, two special values of file are supported: /dev/stderr, which writes the upshot to the standard error, and /dev/stdout, which writes to the standard output.
east This control allows ane to pipage input from a shell command into pattern space. If a substitution was made, the command constitute in pattern infinite is executed and pattern infinite is replaced with its output. A trailing newline is suppressed; results are undefined if the command to be executed contains a null character. This option 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 way.
Grand, chiliad The One thousand modifier to regular-expression matching is a GNU sed extension which causes ^ and $ to match respectively (in add-on to the normal behavior) the empty string after a newline, and the empty cord before a newline. In that location are special character sequences (\` and \') which e'er lucifer the beginning or the end of the buffer. K stands for multi-line.

Less oftentimes-used commands

Though perhaps less frequently used than those in the previous section, some very small yet useful sed scripts tin be congenital 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 whatever of the source-chars with the corresponding grapheme in dest-chars.

Instances of the / (or whatever other character is used instead), \, or newlines can announced 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 Every bit a GNU extension, this command accepts two addresses.

Queue the lines of text which follow this control (each but the last ending with a \, which are removed from the output) to be output at the cease of the current cycle, or when the adjacent input line is read.

Escape sequences in text are processed, and then use \\ in text to print a single backslash.

As a GNU extension, if between the a and the newline at that place is other than a whitespace-\ sequence, so the text of this line, starting at the first not-whitespace character after the a, is taken every bit the showtime line of the text cake. (This enables a simplification in scripting a one-line add.) This extension besides 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 merely the last catastrophe 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 concluding ending with a \, which are removed from the output) in place of the last line (or in identify of each line, if no addresses were specified). A new cycle is started afterward this command is washed, since the pattern space will be deleted.
= Equally a GNU extension, this command accepts ii addresses.

Print out the current input line number (with a trailing newline).

l n Impress the blueprint space in an unambiguous form: not-printable characters (and the \ grapheme) are printed in C-style escaped grade; long lines are split, with a trailing \ character to bespeak the split; the end of each line is marked with a $.

n specifies the desired line-wrap length; a length of 0 (nothing) 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 file proper name Every bit a GNU extension, this command accepts two addresses.

Queue the contents of file name to exist read and inserted into the output stream at the cease of the current cycle, or when the next input line is read. Note that if file proper noun cannot exist 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 proper name, which reads the contents of the standard input.

due west file name Write the blueprint space to file name. Equally a GNU sed extension, ii 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.

The file is created (or truncated) before the offset input line is read; all westward commands (including instances of the westward flag on successful s commands) which refer to the same file name are output without endmost and reopening the file.

D If blueprint space contains no newline, first a normal new cycle as if the d command was issued. Otherwise, delete text in the design space up to the first newline, and restart cycle with the resultant pattern space, without reading a new line of input.
N Add together a newline to the pattern space, and so suspend the next line of input to the pattern space. If at that place 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 Supercede the contents of the hold infinite with the contents of the blueprint space.
H Suspend a newline to the contents of the hold space, and so append the contents of the pattern infinite to that of the hold space.
g Supervene upon the contents of the pattern space with the contents of the concur space.
One thousand 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 agree and blueprint spaces.

Commands for sed gurus

In most cases, use of these commands indicates that you are probably ameliorate off programming in something like awk or Perl. Just occasionally one is committed to sticking with sed, and these commands tin enable i to write quite convoluted scripts.

: label [No addresses allowed with this command.] Specify the location of label for branch commands. In all other respects, a no-op (no operation performed).
b label Unconditionally branch to label. The label may be omitted, in which case the next cycle is started.
t label Branch to label only if there was a successful substitution since the concluding input line was read or conditional branch was taken. The label may be omitted, in which instance the next bike is started.

Commands specific to GNU sed

These commands are specific to GNU sed, then you must use them with intendance and only when yous are sure that the script doesn't need to be ported. They allow you to check for GNU sed extensions or do tasks that are required quite often, notwithstanding are unsupported by standard seds.

due east [command] This control allows one to pipe input from a beat out command into design infinite. Without parameters, the due east command executes the command found in the design space and replaces the blueprint space with the output; a trailing newline is suppressed.

If a parameter is specified, instead, the e control interprets it as a command and sends its output to the output stream (like r does). The command can run across multiple lines, all but the last ending with a dorsum-slash.

In both cases, the results are undefined if the command to be executed contains a null character.

F Print out the file proper name of the current input file (with a trailing newline).
L n This GNU sed extension fills and joins lines in design space to produce output lines of (at well-nigh) n characters, similar fmt does; if north is omitted, the default as specified on the command line is used. This command is considered a failed experiment and unless there is plenty request (which seems unlikely) volition be removed in future versions.
Q [go out-lawmaking] This command but accepts a unmarried accost.

This control is the same as q, merely will non impress the contents of blueprint space. Like q, information technology provides the power to return an exit code to the caller.

This control tin can be useful considering the only culling ways to attain this patently trivial function are to apply the -n option (which can unnecessarily complicate your script) or resorting to the following snippet, which wastes time past reading the whole file without whatever visible effect:

:eat #Quit silently on the last line: $d #Read another line, silently: Northward #Overwrite blueprint space each time to salve retentivity: g b eat.

R file name Queue a line of file name to be read and inserted into the output stream at the end of the electric current bike, or when the side by side input line is read. Note that if file name cannot be read, or if its end is reached, no line is appended, without any error indication.

As with the r command, the special value /dev/stdin is supported for the file name, which reads a line from the standard input.

T label Co-operative to label only if there was no successful substitutions since the final input line was read or provisional co-operative was taken. The label may be omitted, in which case the next wheel is started.
v version This command does nothing, but makes sed neglect if GNU sed extensions are not supported, because other versions of sed practise non implement information technology. Besides, y'all tin specify the version of sed your script requires, such every bit 4.0.v. The default is four.0 considering that is the first version that implemented this command.

This command enables all GNU extensions fifty-fifty if POSIXLY_CORRECT is set up in the environment.

W file name Write to the given file name the portion of the pattern space up to the first newline. Everything said under the w control about file handling holds here too.
z This command empties the content of pattern space. Information technology is unremarkably the aforementioned every bit 's/.*//', but is more efficient and works in the presence of invalid multibyte sequences in the input stream. POSIX mandates that such sequences are not matched by '.', so that there is no portable manner to clear sed's buffers in the middle of the script in well-nigh multibyte locales (including UTF-8 locales).

GNU extensions for escapes in regular expressions

Until now (on this page, anyway), we have simply encountered escapes of the form '\^', for example, which tell sed not to interpret the circumflex (caret) as a special graphic symbol, but rather to have it literally. For some other instance, '\*' matches a single asterisk rather than zero or more backslashes.

This section introduces some other kind of escape—that is, escapes that are applied to a character or sequence of characters that ordinarily are taken literally, and that sed replaces with a special grapheme. This provides a style of encoding not-printable characters in patterns in a visible manner. At that place is no brake on the appearance of non-printing characters in a sed script, merely when a script is being prepared in the shell or by text editing, information technology is usually easier to employ one of the following escape sequences than the binary character it represents:

\a Produces or matches a bel character, that is an "alarm" (ASCII 7).
\f Produces or matches a form feed (ASCII 12).
\n Produces or matches a newline (ASCII 10).
\r Produces or matches a railroad vehicle return (ASCII 13).
\t Produces or matches a horizontal tab (ASCII 9).
\v Produces or matches a so called "vertical tab" (ASCII 11).
\c ten Produces or matches Control- x, where x is any graphic symbol. The precise effect of '\c x' is as follows: if x is a lowercase letter, information technology is converted to uppercase. So bit six of the grapheme (hex twoscore) is inverted. Thus '\cz' becomes hex 1A, just '\c{' becomes hex 3B, while '\c;' becomes hex 7B.
\d thirty Produces or matches a character whose decimal ASCII value is thirty.
\o xxx Produces or matches a character whose octal ASCII value is xxx.
\x twenty Produces or matches a character whose hexadecimal ASCII value is xx.

'\b' (backspace) was omitted considering of the conflict with the existing "word boundary" meaning.

Other escapes match a particular character course and are valid only in regular expressions:

\w Matches any "word" character. A "word" graphic symbol is any letter or digit or the underscore character.
\W Matches whatever "non-word" graphic symbol.
\b Matches a word purlieus; that is, information technology matches if the character to the left is a "word" character and the character to the correct is a "non-word" character, or vice versa.
\B Matches everywhere only on a discussion boundary; that is it matches if the character to the left and the character to the correct are either both "word" characters or both "not-discussion" characters.
\` Matches simply at the showtime of pattern infinite. This option is different from ^ in multi-line style.
\' Matches simply at the end of blueprint infinite. This pick is different from $ in multi-line style.

Sample scripts

Here are some sed scripts to guide you in the art of mastering sed.

Sample script: centering lines

This script centers all lines of a file on 80 columns width. To change that width, the number in \{...\} must be replaced, and the number of added spaces also must be changed.

Note how the buffer commands are used to separate parts in the regular expressions to be matched, which is a common technique.

#!/usr/bin/sed -f # Put 80 spaces in the buffer ane {   x   southward/^$/          /   s/^.*$/&&&&&&&&/   x } # del leading and trailing spaces y/tab/ / s/^ *// south/ *$// # add together a newline and 80 spaces to stop of line G # continue showtime 81 chars (eighty + a newline) southward/^\(.\{81\}\).*$/\1/ # \2 matches half of the spaces, which are moved to the beginning s/^\(.*\)\n\(.*\)\2/\2\1/        

Sample script: increment a number

This script is one of a few that demonstrate how to do arithmetic in sed. This script is indeed possible, but must be done manually.

To increment 1 number you add 1 to last digit, replacing it by the following digit. There is 1 exception: when the digit is a nine the previous digits must be likewise incremented until you don't take a nine.

This solution is very clever and smart because it uses a single buffer; if yous don't have this limitation, the algorithm used in Numbering Lines is faster. It works by replacing abaft nines with an underscore, and so using multiple due south commands to increment the final digit, and then once more substituting underscores with zeros.

#!/usr/bin/sed -f /[^0-9]/ d # replace all leading 9s past _ (any other graphic symbol except digits, could # be used) :d s/ix\(_*\)$/_\1/ td # incr last digit only.  The first line adds a almost-meaning # digit of one if we have to add a digit. # # The tn commands are not necessary, but make the thing # faster southward/^\(_*\)$/1\1/; tn s/eight\(_*\)$/9\1/; tn s/vii\(_*\)$/8\ane/; tn s/6\(_*\)$/7\i/; tn s/v\(_*\)$/6\1/; tn s/4\(_*\)$/5\1/; tn s/3\(_*\)$/4\1/; tn s/2\(_*\)$/3\1/; tn s/i\(_*\)$/two\1/; tn due south/0\(_*\)$/i\1/; tn :n y/_/0/        

Sample script: rename files to lowercase

This script is a pretty foreign use of sed. We transform text, and transform it to be shell commands, and so feed them to shell. Don't worry, even worse hacks are done when using sed. Scripts have fifty-fifty been written converting the output of date into a bc program... So, stranger things take happened.

The chief torso of this is the sed script, which remaps the name from lower to upper (or vice versa) and even checks out if the remapped proper name is the same equally the original proper name. Note how the script is parameterized using shell variables and proper quoting.

#! /bin/sh # rename files to lower/upper case... # # usage: #    move-to-lower * #    movement-to-upper * # or #    move-to-lower -R . #    move-to-upper -R . # assist() {         cat << eof Usage: $0 [-n] [-r] [-h] files... -n      practise nothing, only see what would be done -R      recursive (utilise detect) -h      this message files   files to remap to lower case Examples:        $0 -n *        (run across if everything is ok, then...)        $0 *        $0 -R . eof } apply_cmd='sh' finder='repeat "[email protected]" | tr " " "\n"' files_only= while : do     case "$one" in         -due north) apply_cmd='true cat' ;;         -R) finder='find "[electronic mail protected]" -type f';;         -h) help ; exit 1 ;;         *) break ;;     esac     shift done if [ -z "$1" ]; then         echo Usage: $0 [-h] [-northward] [-r] files...         exit one fi LOWER='abcdefghijklmnopqrstuvwxyz' UPPER='ABCDEFGHIJKLMNOPQRSTUVWXYZ' case `basename $0` in         *upper*) TO=$UPPER; FROM=$LOWER ;;         *)       FROM=$UPPER; TO=$LOWER ;; esac eval $finder | sed -northward ' # remove all trailing slashes s/\/*$// # add ./ if there is no path, only a file name /\//! s/^/.\// # salve path+file name h # remove path southward/.*\/// # practice conversion only on file proper noun y/'$FROM'/'$TO'/ # now line contains original path+file, while # hold space contains the new file name x # add together converted file name to line, which now contains # path/file-name\nconverted-file-proper name G # check if converted file proper name is equal to original file proper noun, # if it is, do non print nothing /^.*\/\(.*\)\n\1/b # now, transform path/fromfile\n, into # mv path/fromfile path/tofile and print it south/^\(.*\/\)\(.*\)\n\(.*\)$/mv "\1\two" "\1\3"/p ' | $apply_cmd        

Sample script: print bash environment

This script strips the definition of the shell functions from the output of the set command in the Bourne-Again beat (bash).

#!/bin/bash set | sed -northward ' :10 # if no occurrence of '=()' print and load next line /=()/! { p; b; } / () $/! { p; b; } # possible start of functions section # save the line in example this is a var similar FOO="() " h # if the next line has a caryatid, we quit because # zero comes later functions n /^{/ q # impress the former line x; p # work on the new line at present 10; bx '

Sample script: reverse characters of lines

This script can reverse the position of characters in lines. The technique moves two characters at a time, hence it is faster than more intuitive implementations.

Note the tx control before the definition of the characterization. This control is frequently needed to reset the flag that is tested by the t control.

#!/usr/bin/sed -f /../! b # Reverse a line.  Begin embedding the line between two newlines due south/^.*$/\ &\ / # Move showtime character at the end.  The regexp matches until # there are cipher or one characters between the markers tx :ten s/\(\n.\)\(.*\)\(.\due north\)/\3\2\ane/ tx # Remove the newline markers s/\n//g        

Sample script: reverse lines of files

This one begins a series of totally useless (however interesting) scripts emulating various Unix commands. This, in detail, is a tac workalike.

Note that on implementations other than GNU sed this script might hands overflow internal buffers.

#!/usr/bin/sed -nf # reverse all lines of input, i.e., beginning line became last, ... # from the 2nd line, the buffer (which contains all previous lines) # is *appended* to current line, so, the order volition be reversed 1! G # on the last line we're done -- print everything $ p # shop everything on the buffer again h        

Sample script: numbering lines

This script replaces 'cat -n'; in fact it formats its output exactly similar GNU true cat does.

Of form this is completely useless for two reasons: first, considering somebody else did it in C (the true cat control), and second, because the post-obit Bourne-trounce script could be used for the same purpose and would be much faster:

#! /bin/sh sed -due east "=" [e-mail protected] | sed -e '   southward/^/      /   N   south/^ *\(......\)\n/\ane  / '        

It uses sed to print the line number, then groups lines two by 2 using N. Of course, this script does not teach as much as the 1 presented below.

The algorithm used for incrementing uses both buffers, then the line is printed every bit soon as possible and then discarded. The number is dissever so that irresolute digits go in a buffer and unchanged ones go in the other; the changed digits are modified in a single stride (using a y command). The line number for the next line is then composed and stored in the concord space, to be used in the next iteration.

#!/usr/bin/sed -nf # Prime the pump on the beginning line x /^$/ s/^.*$/1/ # Add the correct line number before the pattern G h # Format information technology and print it south/^/      / s/^ *\(......\)\northward/\1  /p # Get the line number from concord infinite; add a null # if nosotros're going to add a digit on the adjacent line thousand s/\n.*$// /^nine*$/ s/^/0/ # separate changing/unchanged digits with an 10 s/.9*$/x&/ # continue changing digits in agree space h s/^.*ten// y/0123456789/1234567890/ ten # keep unchanged digits in pattern space due south/x.*$// # compose the new number, remove the newline implicitly added by K G s/\n// h        

Sample script: numbering non-blank lines

Emulating 'cat -b' is well-nigh the aforementioned as 'cat -due north': we only take to select which lines are to be numbered and which are not.

The part that is common to this script and the previous one is not commented to show how of import information technology is to comment sed scripts properly...

#!/usr/bin/sed -nf /^$/ {   p   b } # Aforementioned every bit cat -due north from now x /^$/ s/^.*$/1/ G h s/^/      / due south/^ *\(......\)\n/\one  /p x s/\n.*$// /^9*$/ due south/^/0/ s/.nine*$/10&/ h south/^.*x// y/0123456789/1234567890/ x s/10.*$// Chiliad s/\n// h        

Sample script: counting characters

This script shows another way to do arithmetic with sed. In this instance, we accept to add peradventure large numbers, so implementing this by successive increments would not be viable (and perchance fifty-fifty more complicated to contrive than this script).

The approach is to map numbers to messages, kind of an abacus implemented with sed. 'a's are units, 'b'southward are tens and so on: nosotros add together the number of characters on the current line equally units, then propagate the bear to tens, hundreds, and and then on.

As usual, running totals are kept in concord space.

On the last line, nosotros convert the abacus class back to decimal. For the sake of variety, this is done with a loop rather than with some eighty s commands: first we catechumen units, removing 'a's from the number; then we rotate messages and then that tens get 'a's, and so on until no more than messages remain.

#!/usr/bin/sed -nf # Add due north+1 a's to hold infinite (+1 is for the newline) southward/./a/g H x due south/\north/a/ # Do the behave.  The t's and b's are non necessary, # just they do speed up the thing t a : a;  s/aaaaaaaaaa/b/g; t b; b done : b;  s/bbbbbbbbbb/c/one thousand; t c; b washed : c;  southward/cccccccccc/d/g; t d; b done : d;  s/dddddddddd/e/g; t due east; b washed : e;  due south/eeeeeeeeee/f/1000; t f; b done : f;  s/ffffffffff/g/g; t g; b done : k;  south/gggggggggg/h/g; t h; b washed : h;  south/hhhhhhhhhh//1000 : done $! {   h   b } # On the last line, convert back to decimal : loop /a/! southward/[b-h]*/&0/ due south/aaaaaaaaa/9/ s/aaaaaaaa/8/ s/aaaaaaa/seven/ s/aaaaaa/6/ south/aaaaa/5/ s/aaaa/4/ s/aaa/3/ s/aa/ii/ s/a/1/ : next y/bcdefgh/abcdefg/ /[a-h]/ b loop p        

Sample script: counting words

This script is almost the aforementioned as the previous one, once each of the words on the line is converted to a single 'a' (in the previous script each letter of the alphabet was changed to an 'a').

It is interesting that real wc programs have optimized loops for 'wc -c', and then they are much slower at counting words rather than characters. This script's bottleneck, instead, is arithmetic, and hence the word-counting one is faster (it has to manage smaller numbers).

Again, the common parts are non commented to evidence the importance of commenting sed scripts.

#!/usr/bin/sed -nf # Catechumen words to a'due south s/[ tab][ tab]*/ /m southward/^/ / s/ [^ ][^ ]*/a /m southward/ //g # Append them to hold space H x s/\n// # From here on information technology is the same as in wc -c. /aaaaaaaaaa/! bx;   s/aaaaaaaaaa/b/g /bbbbbbbbbb/! bx;   s/bbbbbbbbbb/c/m /cccccccccc/! bx;   south/cccccccccc/d/g /dddddddddd/! bx;   s/dddddddddd/e/1000 /eeeeeeeeee/! bx;   s/eeeeeeeeee/f/g /ffffffffff/! bx;   s/ffffffffff/g/g /gggggggggg/! bx;   s/gggggggggg/h/g southward/hhhhhhhhhh//chiliad :x $! { h; b; } :y /a/! due south/[b-h]*/&0/ s/aaaaaaaaa/nine/ s/aaaaaaaa/8/ s/aaaaaaa/7/ s/aaaaaa/6/ s/aaaaa/5/ due south/aaaa/4/ s/aaa/3/ s/aa/2/ s/a/ane/ y/bcdefgh/abcdefg/ /[a-h]/ by p        

Sample script: counting lines

Sed gives us 'wc -l' functionality for free. Hither is the code:

#!/usr/bin/sed -nf $=        

Sample script: printing the first lines

This script is probably the simplest useful sed script. It displays the first ten lines of input; the number of displayed lines is right before the q command.

#!/usr/bin/sed -f 10q        

Sample script: printing the last lines

Printing the last north lines rather than the first is more complex merely indeed possible. The due north is encoded in the second line, before the bang ("!") character.

This script is similar to the tac script (above) in that it keeps the concluding output in the concord infinite and prints it at the cease:

#!/usr/bin/sed -nf 1! {; H; grand; } 1,10 !s/[^\due north]*\due north// $p h        

Mainly, the scripts keeps a window of 10 lines and slides it past adding a line and deleting the oldest (the substitution command on the 2nd line works like a D command simply does not restart the loop).

The "sliding window" technique is a very powerful mode to write efficient and complex sed scripts, because commands similar P would require a lot of work if implemented manually.

To introduce the technique, which is fully demonstrated in the residual of this chapter and is based on the North, P and D commands, hither is an implementation of tail using a simple "sliding window."

This looks complicated but in fact the working concept is the same as the last script: later we have kicked in the appropriate number of lines, however, we stop using the concord space to keep inter-line land, and instead use N and D to slide design space past one line:

#!/usr/bin/sed -f 1h 2,x {; H; g; } $q one,9d N D        

Note how the outset, second and fourth line are inactive after the first 10 lines of input. Later that, all the script does is: exiting on the last line of input, appending the next input line to pattern space, and removing the first line.

Sample script: brand indistinguishable lines unique

This script is an example of the fine art of using the N, P and D commands, probably the virtually difficult to master.

#!/usr/bin/sed -f h :b # On the last line, print and exit $b N /^\(.*\)\northward\1$/ {     # The two lines are identical.  Undo the effect of     # the n command.     one thousand     bb } # If the N command had added the last line, print and exit $b # The lines are unlike; impress the get-go and get # dorsum working on the 2nd. P D        

Equally you can see, nosotros maintain a 2-line window using P and D. This technique is oft used in advanced sed scripts.

Sample script: print duplicated lines of input

This script prints simply duplicated lines, similar 'uniq -d'.

#!/usr/bin/sed -nf $b Due north /^\(.*\)\n\i$/ {     # Print the get-go of the duplicated lines     south/.*\n//     p     # Loop until we get a different line     :b     $b     N     /^\(.*\)\n\1$/ {         south/.*\due north//         bb     } } # The terminal line cannot exist followed by duplicates $b # Plant a different one.  Leave it lone in the pattern space # and become back to the pinnacle, hunting its duplicates D        

Sample script: remove all duplicated lines

This script prints only unique lines, like 'uniq -u'.

#!/usr/bin/sed -f # Search for a duplicate line --- until that, impress what you find. $b N /^\(.*\)\north\1$/ ! {     P     D } :c # Got ii equal lines in design infinite.  At the # end of the file we go out $d # Else, we continue reading lines with N until nosotros # find a unlike one s/.*\due north// N /^\(.*\)\n\1$/ {     bc } # Remove the concluding case of the duplicate line # and get back to the height D        

Sample script: squeezing bare lines

As a final instance, here are iii scripts, of increasing complexity and speed, that implement the same part every bit 'cat -southward', that is squeezing blank lines.

The outset leaves a blank line at the showtime and finish if there are some already.

#!/usr/bin/sed -f # on empty lines, bring together with next # Note in that location is a star in the regexp :x /^\northward*$/ { N bx } # now, squeeze all '\north', this can exist also washed by: # southward/^\(\due north\)*/\1/ southward/\n*/\ /        

This one is a bit more than complex and removes all empty lines at the beginning. It does leave a single blank line at stop if one was in that location.

#!/usr/bin/sed -f # delete all leading empty lines 1,/^./{ /./!d } # on an empty line we remove it and all the following # empty lines, but 1 :x /./!{ N due south/^\north$// tx }        

This removes leading and abaft blank lines. It is also the fastest. Note that loops are completely done with due north and b, without relying on sed to restart the script automatically at the end of a line.

#!/usr/bin/sed -nf # delete all (leading) blanks /./!d # get here: so there is a non empty :x # impress information technology p # become next n # got chars? print it again, etc... /./bx # no, don't have chars: got an empty line :z # become next, if last line we cease hither so no trailing # empty lines are written due north # also empty? then ignore it, and get next... this will # remove ALL empty lines /./!bz # all empty lines were deleted/ignored, simply we have a not empty.  As # what we want to do is to squeeze, insert a blank line artificially i\ bx        

GNU sed'due south limitations (and non-limitations)

For those who want to write portable sed scripts, be enlightened that some implementations are known to limit line lengths (for the pattern and hold spaces) to be no more than than 4000 bytes. The POSIX standard specifies that conforming sed implementations shall support at least 8192 byte line lengths. GNU sed has no congenital-in limit on line length; as long as it can allocate more (virtual) memory, you can feed or construct lines as long as you lot like.

Still, recursion is used to handle subpatterns and indefinite repetition. This indicates the bachelor stack infinite may limit the size of the buffer that can be processed by sure patterns.

Extended regular expressions

The only departure between basic and extended regular expressions is in the behavior of a few characters: '?', '+', parentheses, and braces ('{}'). While basic regular expressions crave these to be escaped if you want them to bear as special characters, when using extended regular expressions you lot must escape them if you want them to match a literal character.

For example:

abc? Becomes 'abc\?' when using extended regular expressions. It matches the literal cord 'abc?'.
c \+ Becomes 'c +' when using extended regular expressions. It matches one or more 'c'south.
a\{3,\} Becomes 'a{iii,}' when using extended regular expressions. It matches three or more 'a's.
\(abc\)\{2,iii\} Becomes '(abc){two,3}' when using extended regular expressions. It matches either 'abcabc' or 'abcabcabc'.
\(abc*\)\1 Becomes '(abc*)\i' when using extended regular expressions. Backreferences must still be escaped when using extended regular expressions.

Examples

sed Thousand myfile.txt > newfile.txt

Double-spaces the contents of file myfile.txt, and writes the output to the file newfile.txt.

sed = myfile.txt | sed 'N;s/\n/\. /'

Prefixes each line of myfile.txt with a line number, a period, and a space, and displays the output.

sed 'southward/test/example/g' myfile.txt > newfile.txt

Searches for the word "examination" in myfile.txt and replaces every occurrence with the word "example".

sed -n '$=' myfile.txt

Counts the number of lines in myfile.txt and displays the results.

awk — Interpreter for the AWK text processing programming language.
ed — A simple text editor.
grep — Filter text which matches a regular expression.
replace — A string-replacement utility.

bellasisemaked.blogspot.com

Source: https://www.computerhope.com/unix/used.htm

0 Response to "Unix Command Reading Each New Line in Text File to Run in C Program Without Scripting"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel