Date: Fri, 15 Sep 2006 23:44:40 +0200 From: J65nko <j65nko@gmail.com> To: freebsd-questions@freebsd.org Subject: Re: OT: awk/sed: how to use a variable in an address range? Message-ID: <19861fba0609151444j48fbfa0fpd30345758f64455a@mail.gmail.com> In-Reply-To: <45094622.7010803@uni-mainz.de> References: <45094622.7010803@uni-mainz.de>
next in thread | previous in thread | raw e-mail | index | archive | help
On 9/14/06, O. Hartmann <ohartman@uni-mainz.de> wrote: [snip] > To keep a small shell script portable I use awk for separating an ASCII > file from a home brewn scientific model software. The datasets of the > output is enclosed by > > /begin_data_set_##/ > . > . > . > /end_data_set_##/ > > ## is a two-digit counter, but not necessesaryly equidistant. > > I would like to separate the file contaning all datasets via awk or sed > into appropriate files - this is my intention, but I failed. > > the simplest way - in theory and in my limitit ability of using sed or > awk - is to print all lines between the (sed/awk) addresses > > /begin_data_set_##/ > ... > /end_data_set_##/ > > but this does not work due to i cannot use variables in the address > range specifiers neither in awk nor in sed like this: > > awk -v nc=$NUMBER '/\/begin_data_set_nc\//,/\/end_data_set_nc\// { > do-something-in-awk}' $input_file > $output_file_$NUMBER > > nc in this example is set to the counter of the desired dataset. > > I would like to use SED or AWK only due to portability reasons. [snip] You have to prefix the variable with "$" and use double quotes instead of single quotes. The shell will expand a variable within double quotes, but one within single quotes $ cat data /start_1/ This is dataset 1 /end_1/ /start_2/ This is dataset 2 /end_2/ /start_3/ This is dataset 3 /end_3/ $ cat sed_extract NR=$1 sed -ne "/\/start_$NR\//,/\/end_$NR\//p" data $ sh -vx sed_extract 3 NR=$1 + NR=3 sed -ne "/\/start_$NR\//,/\/end_$NR\//p" data + sed -ne /\/start_3\//,/\/end_3\//p data /start_3/ This is dataset 3 /end_3/ $ sh -vx sed_extract 2 NR=$1 + NR=2 sed -ne "/\/start_$NR\//,/\/end_$NR\//p" data + sed -ne /\/start_2\//,/\/end_2\//p data /start_2/ This is dataset 2 /end_2/ You were close ;)
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?19861fba0609151444j48fbfa0fpd30345758f64455a>