Search code examples
bashshellcentos

Find and fill missing line up to nth line with text


i need a bash script to find a text file in a folder (current level only) that has less than 10 line and add n/a to fill up to 10 line, while ignore txt file that has all 10 line.

i tried using 'find' to find txt file line, add to array then doing loop in the end i got headache (!^.^)

original
1. line
2. line
3. line
4. line

expected
1. line
2. line
3. line
4. line
5. n/a
..
10. n/a

tried with

array=( $(find . -mindepth 1 -maxdepth 1 -name '*.txt' | xargs wc -l) )

Solution

  • Something like this:

    #!/usr/bin/env bash
    
    limit=10
    for f in ./*.txt; do
      total="$(wc -l <"$f")"
      ((total >= limit)) && {
        printf >&2 '%s has %d lines, skipping!\n' "$f" "$total" &&
        continue
      }
      while ((total++ < limit)); do
        printf '%d. n/a\n' "$total"
      done >> "$f"
    done