0

I am new at this and is learning how to get the variable. How do i get print variable parts right inside command substitution? Thanks.

echo "Enter number of parts:"
read parts
echo "Enter filename:"
read filename

LINES=$(wc -l $filename | awk '{print $1/$parts}' OFMT="%0.0f")

echo $LINES
Potential Coder
  • 91
  • 3
  • 11

3 Answers3

4

The problem is twofold. First, bash won't expand variables in single quotes, so $parts is passed literally to awk. You should use double quotes instead. That, however, brings up a different issue. Bash is expanding the variables before calling awk:

LINES=$(wc -l $filename | awk "{print $1/$parts}" OFMT="%0.0f")
                                      -- ------
                                       |    |-> $parts as defined in
                                       |         your script
                                       |------> $1, the first positional 
                                                parameter of your bash script.

So, in order to use the actual first field of the file, you need to escape the $1:

LINES=$(wc -l $filename | awk '{print \$1/$parts}' OFMT="%0.0f")

Or pass the variable to awk explicitly:

LINES=$(wc -l $filename | awk '{print $1/parts}' OFMT="%0.0f" parts=$parts)
terdon
  • 3,260
  • 5
  • 33
  • 57
2

Pass your bash variable in with -v.

Also, you can let awk count the lines in the file for you - it will know that at the end in the NR variable...

awk -v p=$parts 'END{print int(NR/p)}' file
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
1

Try:

LINES=$(wc -l $filename | awk -v PART=$parts '{print $1/PART}' OFMT="%0.0f")
Fazlin
  • 2,285
  • 17
  • 29