0

I have the following awk statement

awk '/^string$/{i=1;next} i && i++ <= 2' file

This will search for string and then print 2 lines down.

So as an example

$ cat file
string
aaa
bbb
ccc

$ awk '/^string$/{i=1;next} i && i++ <= 2' file
$ bbb

What I want to do is change the 2 into a counter, so that I can iterate 10 lines down each time. For example

for i in {1..5}
do
   awk '/^111$/{i=1;next} i && i++ <= $i' file
done

That of course does not work and I am not sure if this is even possible as the command is encapsulated in the loop.

For reference, what I want to do is check within a config file (file.cfg) for a value [header] and see if a variable is enabled (variable = enabled)

For example

cat file.cfg
[header]
# nothing
variable = enabled

I guess the key attributes are that [header] will be on an undetermined line (it could be line 1 it could be line 122)

And variable is not always going to be the second line after [header], some people might put it 7 places down, others 2 places down.

Hope that makes sense and thanks in advance.

1

If your config file is build up using [header] lines followed by variable=value lines you can use the following command to get all the values from a specific section:

sed -n '/^\[header\]/,/^\[/p' /path/to/file.cfg|grep -vE '?\s?[;#]'

The sed part will filter all the lines from the [header] up to (and including) the next line starting with a [ character. The grep command will filter out lines which have a ; or # as starting character.

Instead of sed you might use awk. Based on an earlier answer on question https://stackoverflow.com/questions/17988756/how-to-select-lines-between-two-marker-patterns-which-may-occur-multiple-times-w:

awk '/\[header\]/{print; flag=1; next}/\[/{flag=0}flag' file.cfg

You can append the grep command as above if you want to filter out commented lines.

1

In the shell you can concatenate strings if they are juxtaposed with no intervening spaces, eg:

echo 'abc$def'"and so on"
abc$defand so on

So in your example simply exit the (') string and start a (") string so your $i can be interpolated by the shell:

awk '/^111$/{i=1;next} i && i++ <= '"$i" file

Also, if your [header] strings are easily distinguishable from the data lines, you can just use awk's ability to run a command when between two lines. Eg:

seq 10 | awk '/6/,/9/{print}'

will print lines 6 to 9. So instead of doing your own counting, and assuming [header1] is a typical header syntax (so you need to escape the [), you could use something like

awk '/^\[header1]/,/^\[header2]/ { print }'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.