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
  • What are you trying to do? Count how many times, 'a' appears in the file a.txt, and then output it back into a.txt? –  Oct 20 '16 at 17:46
  • @bc2946088 it's not like that. My aim is to store command and output as key value. – Gibbs Oct 20 '16 at 17:48
  • I haven't a clue what you're trying. I don't know that anyone else will either. Maybe adjust your question. –  Oct 20 '16 at 17:51
  • @bc2946088 Updated – Gibbs Oct 20 '16 at 18:02

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
  • 17,900