Learn R Programming

rsed (version 0.1.2)

sed_insert: Insert one or more lines

Description

Insert one or more lines

Usage

sed_insert(stream, after, insertion, warn = FALSE, ...)

Arguments

stream

A character vector, each element typically (but not necessarily) containing the text from a single line in a file, which can be generated via readLines.

after

An integer or character string that designates where insertion is added to stream. If after is numeric, it designates the line (or element) number in stream after which the insertion will be placed. The numeric value of after must be in [0:length(stream)]. To make an insertion at the very beginning of stream, use after = 0. If after is a character string, the insertion is placed after the first element in stream that contains the string, where matching is obtained using grep.

insertion

A character vector that will be inserted into the stream after element after. Each element in the vector would correspond to a separate line in the file.

warn

If TRUE, warning messages are produced if insertion fails due to mispecifification of after.

Additional named arguments to grep, which are applicable if after is a character string. In other words, grep is used to search for the first instance of after.

Value

The new stream with the insertions added. If the insertion fails because after is specified incorrectly, stream is returned unchanged.

Details

sed_insert only accomodates a single insertion point. Multiple lines may be inserted, but only one insertion point is allowed, which is why length(insertion) must be 1. To make insertions at multiple locations, sed_insert can be called repeatedly on the same string as needed.

See Also

sed_replace, sed_substitute, sed_comment, streamEdit

Examples

Run this code
# NOT RUN {
################################################################################
# Let's create an example stream we can edit
################################################################################
stream <- c("Here's a line",
           "And another line",
           "Line after which we'll insert a string",
           "A line after which we'll insert another string",
           "A final line")
as.stream(stream)

# Insert a string using line numbers
stream <- sed_insert(stream, after = 3, "Here's the first insertion")
stream

# Insert a stream by searching for a string
stream <- sed_insert(stream,
                    c("Here's the second insertion",
                      "",
                      "Another line of the second insertion after the blank line"),
                    after = "insert another")
stream
# }

Run the code above in your browser using DataLab