Bootstrap FreeKB - Bash (Scripting) - do something range match
Bash (Scripting) - do something range match

Updated:   |  Bash (Scripting) articles

Let's say foo.txt or the $foo variable contain the following text.

Line 1 a
Line 2 a
Line 3 a
Line 4 a
Line 1 b
Line 2 b
Line 3 b
Line 4 b

 

The following sed statement can be used to print the every line that contains "Line 1". Typically, you would use grep for this kind of filtering.

~]# sed -n '/Line 1/ p' foo.txt
Line 1 a
Line 1 b

 

The following sed statement will print every line that contains "Line 1" and "Line 3".

~]# sed -n '/Line 1/ p; /Line 3/ p' foo.txt
Line 1 a
Line 3 a
Line 1 b
Line 3 b

 

The following sed statement can be used to print the text between Line 1 and Line 3.

~]# sed -n '/Line 1/, /Line 3/ p' foo.txt
Line 1 a
Line 2 a
Line 3 a
Line 1 b
Line 2 b
Line 3 b

 

The following sed statement will print only line 1 and everything from line 3 through line 4.

~]# sed -n '/Line 1/ p; /Line 3/, /Line 4/ p' foo.txt
Line 1 a
Line 3 a
Line 4 a
Line 1 b
Line 3 b
Line 4 b

 

The following sed statement can be used to delete the text between Line 2 and Line 4.

sed -i '/Line 1/, /Line 3/ d' foo.txt

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 59d13d in the box below so that we can be sure you are a human.