jnorth
jnorth

Reputation: 115

count string and print to new outfile

I am attempting to count the occurrences of a particular string "PhD" within a file 'X', take that count# (e.g. 3), and print/cat to the beginning of another file, 3 times, this particular string

Graduate StudentID 1
Graduate StudentID 2
Graduate StudentID 3

The numbers after StudentID reflect the counting.

My hopeless attempt to this point is ($OUT was supposed to the file written to) and I am not sure how to resolve the (obvious) resultant errors.

find /home/college/Applications/Graduate -name "*.inp" -exec sed 's/[PhD]//g' input | uniq -c print >$OUT {$1} \;

Upvotes: 0

Views: 38

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52132

Here is how I would do it:

#!/bin/bash

# Count number of occurrences
# Use -o | wc -l instead of -c to count multiple occurrences in same line
count=$(grep -ro 'PhD' --include='*.inp' /home/college/Applications/Graduate | wc -l)

# Intermediate file
tmp=$(tempfile)

# Output file
out=outfile.txt

{
    # Print header lines
    for (( i = 1; i <= count; ++i )); do
        printf '%s %d\n' 'Graduate StudentID' "$i"
    done

    # Print existing contents
    cat "$out"
} > "$tmp"

# Rename intermediate file
mv "$tmp" "$out"

This assumes that your output file name is outfile.txt

Upvotes: 1

Related Questions