Sed Find and Display Text Between Two Strings or Words

w‮l.ww‬autturi.com
Sed Find and Display Text Between Two Strings or Words

To find and display text between two strings or words using sed, you can use the following command:

sed -n '/string1/,/string2/p' file

This command will search the file for lines that contain the string string1, and then print all lines until it finds a line that contains the string string2. The -n option suppresses the default output of sed, and the p command prints the selected lines.

For example, consider the following input file:

This is the first line.
This is the second line.
This is the third line.
This is the fourth line.

To find and display the lines between second and fourth, you can use the following command:

sed -n '/second/,/fourth/p' file

This will output the following lines:

This is the second line.
This is the third line.
This is the fourth line.

You can also use the -n option with the ! operator to invert the selection, and print all lines except those between the two strings:

sed -n '/string1/,/string2/!p' file

This will print all lines in the file except those that contain the strings string1 and string2.

By using the sed command with the -n and p options, you can find and display text between two strings or words in a file. This can be useful for extracting specific information from a large file or for processing text data in a script.

Created Time:2017-10-30 14:27:18  Author:lautturi