1

NOTE: I am a noob at bash scripts and the awk command - please excuse any dumb mistakes I make.

I am unable to substitute shell variables into my awk pattern. I am trying to scan through a file, find the first occurence of a specific string in the file, and print each line that succeed it in order until it hits an empty string/line.

I don't know the string I am searching for in advance, and I would like to substitute in that variable.

When I run this with the string directly specified (e.g "< main>:"), it works perfectly. I've already searched on how awk patterns work, and how to substitute in variables. I've tried using the -v flag for awk, directly using the shell variable - nothing works.

funcName="<${2}>:"

awk=`awk -v FN="$funcName" '/FN/,/^$/' "$ofile"`

rfile=search.txt

echo -e "$awk" > "$rfile"

The error is just that nothing prints. I want to print all the lines between my desired string and the next empty line.

Inian
  • 80,270
  • 14
  • 142
  • 161
v0rtex20k
  • 1,041
  • 10
  • 20

1 Answers1

2

Could you please try following, haven't tested it because no clear samples but should work.

funcName="<${2}>:"
awk_result=$(awk -v FN="$funcName" 'index($0,FN){found=1} found; /^$/{found=""}' "$ofile")
rfile=search.txt
echo -e "$awk_result" > "$rfile"

Things fixed in OP's attempt:

  1. NEVER keep same name of a variable as a binary's name or on a keyword's name so changed awk variable name to awk_result.
  2. Use of backticks is depreciated now, so always wrap your variable for having values in var=$(......your commands....) fixed it for awk_result variable.
  3. Now let us talk about awk code fix, I have used index method which checks if value of variable FN is present in a line then make a FLAG(a variable TRUE) and make it false till line is empty as per OP's ask.
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • 1
    You are a lifesaver <3 thank you so much. I'm curious though - why were such drastic changes needed? All the sites I checked made it seem like you could just directly use the value you -v'd – v0rtex20k Oct 29 '19 at 02:38
  • 2
    @victor__von__doom drastic changes were needed because 1) you were trying to use the variable as a regexp when you needed to use it as a string and 2) you were trying to use a range expression when a flag is always the better approach (see https://stackoverflow.com/q/23934486/1745001). – Ed Morton Oct 29 '19 at 13:43