Join David D. Levine for an in-depth discussion in this video Controlling printing with -n and the "p" modifier, part of SED Essential Training.
- In this lesson, we'll discuss SED's command-line flags. - n supresses the default printing of each line. - e allows specifying multiple commands on a single command-line, and -f specifies a file of commands. Like most Unix commands, SED accepts command-line flags, or options, which are special command-line arguments beginning with a dash. These flags, if used, appear between the word "SED" and the following command, separated from both by a space.
Usually SED prints or outputs each line. If the "s" command makes any changes to the line, it is printed after the changes are applied. The -m flag tells SED not to print anything unless explicitly specified. To specify printing, you add the "p" modifier to a command, which tells SED to print the output of the command. For example, as you've seen earlier, sed 's/the/THE/' dukeofyork.txt replaces the first lowercase "the" on each line with all-caps "THE".
However as you see, even lines that are not changed are printed. If you add the -n flag... this produces not output at all. The -n flag prevents anything from being printed unless explicitly specified. We'll add a "p" modifier to the end of the "s" command which says that after you've made that substitution, you should print it. So in this case, it prints only the lines in which the specified substitution occurred to be printed.
Note that the first two lines of the file that do not include lowercase "the" were not printed in this case. The "p" modifier can be combined with the "g" modifier in either order. For example, we can do... change "the" to "THE", print it globally. This globally substitutes lowercase "the" for uppercase and prints it where the substitution is made. But again, lines in which no "the's" occur are not printed. Or, you could do the same thing with, instead of "pg"...
you could do "gp", and it produces exactly the same effect. Both change every lowercase "the" to all caps, printing only the changed lines.
- Understanding input, output, files, and pipes
- Modifying the "s" command
- Using character classes and quantifiers
- Controlling printing
- Reading and writing files
- Appending, inserting, and editing entire lines
- Writing programs in SED
- Using advanced programming commands