Issue
I have a file that has marked sections with a ** preceding the title like this, containing various questions:
**Animals
What kind of food do pigs eat?
Where to koalas live?
**Food
Who made the world's largest pizza?
Where is cheese made?
What kind of bread is popular in France?
Given the question as a variable, such as "Where is cheese made?" how can I return the name of the section that question is found under, e.g. "Food" would be the output?
Solution
Could you please try following.
awk -v var="Where is cheese made?" 'index($0,var) && !/^\*\*/{print val;next} /^\*\*/{sub(/^\*\*/,"");val=$0}' Input_file
We could mention variable -v var="...."
which you want to look and print its respective **
line's value.
Adding a non-one liner form of above solution.
awk -v var="Where is cheese made?" '
index($0,var) && !/^\*\*/{
print val
next
}
/^\*\*/{
sub(/^\*\*/,"")
val=$0
}' Input_file
Explanation: Adding explanation for above code here.
awk -v var="Where is cheese made?" ' ##Starting awk program here and mentioning variable named var whose value if whereis cheese made?
index($0,var) && !/^\*\*/{ ##Using index out of the box function of awk programming to get a match of variable var in current line and making sure line is NOT starting from *
print val ##Printing variable val here.
next ##next will skip all further statements from here.
}
/^\*\*/{ ##checking condition if a line starts from * then do following.
sub(/^\*\*/,"") ##Substituting starting ** with NULL here.
val=$0 ##Creating variable val whose value if current line.
}' file ##Mentioning Input_file name here.
Answered By - RavinderSingh13