Search code examples
bashdivisionwc

What is the shortest one-liner to divide the line count of one file by another in bash?


In a bash shell, I am trying to write a short one-liner to divide the line count of one file by the line count of another. I would like show at least two decimal places from floating-point division.

In other words, I would like a one-liner to print the percentage of one file's line count of another.

For example, if I have a first file (first.txt) with 25 lines and a second file (second.txt) with 100 lines, the one-liner would output .25.


Solution

  • First some test material:

    $ for i in {1..25} ; do echo $i >> first ; done
    $ for i in {1..100} ; do echo $i >> second ; done
    

    Then some awk:

    $ awk 'END{print(NR-FNR)/FNR}' first second
    0.25
    

    NR is the total number of records in both files. At the END FNRis the number of records in the latter file, so (NR-FNR)/FNR is the record count of the first file divided by the record count of the second.

    Other than the solutions provided here, you need to take your question to the code golf course .