Edited the question to try and make things clearer
I have a file that looks like this:
BEGIN
Block name : Block1
Var names : var1 var2 var3
var1 32.7
var2 12.2
var3 65.4
END
BEGIN
Block name : Block43
Var names : bar55 foo3
bar55 654.555
foo3 23.4
END
BEGIN
Block name : Block66
Var names : bar2
bar2 33.0987
END
The final output should be:
Block1 has a var named var1 and its value is 32.7
Block1 has a var named var2 and its value is 12.2
Block1 has a var named var3 and its value is 65.4
Block43 has a var named bar55 and its value is 654.555
Block43 has a var named foo3 and its value is 23.4
Block66 has a var named var1 and its value is 33.0987
I do not know the size of the block or how many vars it has.
I do know for certain that each block is surrounded by a BEGIN and END lines.
Is there a way to parse the file to individual blocks and loop through them?
Something in the lines of :
for block in file; do
block_name=$(echo $block | grep 'Block' | cut -d ":" -f2)
vars=$(echo $block | grep 'Var' | cut -d ":" -f2)
for var in $vars;do
var_value=$(echo $block | grep '^$var')
echo "$block_name has a var named $var and its value is $var_value"
done
done
The closest answer to my question was using either sed or awk to get the first instance of a block and then quitting.
I am looking to get information from every block that is surrounded by BEGIN and END.
Thanks for your help.
awk '/foo/{print $2}' file
would work as well asgrep 'foo' file | cut -d " " -f2
. Can you explain (or create a better example) where these won't work and why you need to iterate over the lines between BEGIN and END? – pLumo Jan 27 '21 at 12:21***
? – terdon Jan 27 '21 at 12:35