0
[Dd])   
echo"What is the record ID?" 
read rID
numA= awk -f "%" '{print $1'}< practice.txt

I cannot figure out how to set numA = to the output of the awk in order to compare rID and numA. numA is equal to the first field of a txt file which is separated by %. Any suggestions?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116

4 Answers4

0

this is the correct syntax.

numA=$(awk -F'%' '{print $1}' practice.txt)

however, it will be easier to do comparisons in awk by passing the bash variable in.

awk -F'%' -v r="$rID" '$1==r{... do something ...}' practice.txt

since you didn't specify any details it's difficult to suggest more...

to remove rID matching line from the file do this

awk -F'%' -v r="$rID" '$1!=r' practice.txt > output

will print the lines where the condition is met ($1 not equal to rID), equivalent to deleting the ones which are equal. You can mimic in place replacement by

awk ... practice.txt > temp && mv temp practice.txt

where you fill in ... from the line above.

karakfa
  • 66,216
  • 7
  • 41
  • 56
0

You can capture the output of any command in a variable via command substitution:

numA=$(awk -F '%' '{print $1}' < practice.txt)

Unless your file contains only one line, however, the awk command you presented (as corrected above) is unlikely to be what you want to use. If the practice.txt file contains, say, answers to multiple questions, one per line, then you probably want to structure the script altogether differently.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

You don't need to use awk, just use parameter expansion:

numA=${rID%%\%*}
Ell
  • 927
  • 6
  • 10
0

Try using

$ numA=`awk -F'%' '{ if($1 != $0) { print $1; exit; }}' practice.txt`

From the question, "numA is equal to the first field of a txt file which is separated by %"

  • -F'%', meaning % is the only separator we care about
  • if($1 != $0), meaning ignore lines that don't have the separator
  • print $1; exit;, meaning exit after printing the first field that we encounter separated by %. Remove the exit if you don't want to stop after the first field.