Reputation: 515
var="int foo(float y, bool k)"
awk -v start="$var" '
$0 ~ start ,$0 ~ /}/{
print
if($0 ~ start ){ startLine=FNR }
if($0~/}/){
print "The content is between lines " startLine " and " FNR
exit
}
}' $file
I want to search for a string in a file, but because the string contains parentheses it recognizes them as a operator rather than a character. I tried this
var="int foo\(float y, bool k\)"
and it does solve the issue, but my var isn't always the same so in that case I would neeed some code that adds a backslash before parentheses. Is there any other solution?
Upvotes: 0
Views: 82
Reputation: 133600
Based on your shown samples, could you please try following. Quote your shell variable inside '...'
(single quotes) to make characters inside literal character. Also I have changed approach here and used index
rather than using range method of awk
this is more suitable on this kind of situations.
start='int foo(float y, bool k)'
awk -v start="$start" '
index($0,start){
found=1
startLine=FNR
}
found{
val=(val?val ORS:"")$0
}
$0 ~ /}/{
if(val){ print val }
print "The content is between lines " startLine " and " FNR
exit
}' Input_file
Upvotes: 2