Search code examples
bashvariablesawkcommand-substitution

Pass variable in awk inside command substitution


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

Solution

  • 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)