0

Commands executed:

    cat a1.txt | grep a | wc -l >> a.txt
    cat b.txt | grep a | wc -l >> a.txt
    cat c.txt | grep a | wc -l >> a.txt

I want count and the command to append to a.txt.

like

Expected file output: Assume 100,200,300 are counts.

cat a1.txt | grep a | wc -l  100
cat b.txt | grep a | wc -l 200
cat c.txt | grep a | wc -l  300
Gibbs
  • 125
  • 9

1 Answers1

0

Either

  1. use the script command to capture the terminal, and then edit the results, or

  2. store the command in a variable and then evaluate the command:

    cmd='cat a1.txt | grep a | wc -l'
    printf "%s\t%s\n" "$cmd" "$(eval "$cmd")" >> a.txt
    

    Generalizing this:

    print_and_do() { local cmd="$1"; printf "%s\t%s\n" "$cmd" "$(eval "$cmd")"; }
    {
        print_and_do "cat a1.txt | grep a | wc -l"
        print_and_do "cat b.txt | grep a | wc -l"
        print_and_do "cat c.txt | grep a | wc -l"
    } >> a.txt
    

Are you aware that cat a1.txt | grep a | wc -l can be written as:

grep -c a a1.txt
glenn jackman
  • 18,218