Martin McFly De Luca Martin McFly De Luca - 6 months ago 10
Bash Question

Reading from A to B, but stop at the first occurrence of B

I'm trying to do a shell script that reads from a file from a string A to a B string. The string A I'm sure that is UNIQUE, but the B string is repeated more than one time.

I'm reading from a file that contains a lot of CREATE queries.

each query ends with (my String B)


); ------------------------


String A is composed this way:

CREATE MULTISET TABLE DBNAME.TABLENAME


so I read with sed from A to B

sed -n "/$FROMSTR/,/$TOSTR/p" $2 >> querytest.txt


I want to stop to the first occurrence of
$TOSTR
(String B)

Answer

In place of:

sed -n "/$FROMSTR/,/$TOSTR/p"

use:

sed -n "/$FROMSTR/,\${p; /$TOSTR/q}"

This prints from the first occurrence of $FROMSTR to the last line $ except that it quits when it sees the first occurrence of $TOSTR.

Aside: You should be sure that you trust the source of FROMSTR and TOSTR. If either variable contained sed-active characters, the result might not be what you want.

Example 1

As a simple example:

$ FROMSTR=2; TOSTR=4; seq 10 | sed -n "/$FROMSTR/,\${p; /$TOSTR/q}"
2
3
4

Example 2

As an exampled closer to your actual input, consider this test file:

$ cat file
1
CREATE MULTISET TABLE DBNAME.TABLENAME
2
3
); ------------------------
4

And run this command:

$ FROMSTR="CREATE MULTISET TABLE DBNAME.TABLENAME"
$ TOSTR="); ------------------------"
$ sed -n "/$FROMSTR/,\${p; /$TOSTR/q}" file
CREATE MULTISET TABLE DBNAME.TABLENAME
2
3
); ------------------------

Example 3

Consider this test file:

$ cat file
1
CREATE MULTISET TABLE DBNAME.TABLENAME
2
); ------------------------
); ------------------------
3
CREATE MULTISET TABLE DBNAME.TABLENAME
4
); ------------------------
5

We define our variables:

$ FROMSTR="CREATE MULTISET TABLE DBNAME.TABLENAME"
$ TOSTR="); ------------------------"

And, run our code:

$ sed -n "/$FROMSTR/,\${p; /$TOSTR/q}" file
CREATE MULTISET TABLE DBNAME.TABLENAME
2
); ------------------------