1

I have the following text file:

(Employee Ashley)

insert text here

(Employee Bob)

insert text here

(Employee Joseph)

insert text here

I would like to take the text for each "employee" and save it to a new file. I can manually count the number of employees if that's necessary. How can I do this all from terminal?

I was thinking of "awk" then some way of detecting the open parenthesis as that is the only thing that has the text in between and then in file directory > outfile directory

Could someone help me tie up the loose ends?

2 Answers 2

2
while read -r line; do
    if [[ $line == "(Employee "*")" ]]; then
        t="${line#(Employee }"
        t="${t%)}"
        fn="${t}.txt"
    fi
    echo "$line" >>$fn
done <original_file.txt

This will put the text in Ashley.txt, Bob.txt, Joseph.txt, &c.

2
  • I like the approach, though I suspect they just want all the names in a single file, which your answer can be easily adapted to do Commented Sep 15, 2015 at 23:18
  • I really like this approach, I actually have this in mind for something else. Thank you! Commented Sep 19, 2015 at 15:22
1
awk ' /^\(Employee/ { FILENAME="";
                      for ( i=2 ; i<=NF; i++)
                         FILENAME=FILENAME $i;
                      FILENAME=substr(FILENAME,1,length(FILENAME)-1) ".txt";
                    }
     !/^\(Employee/ { print >> FILENAME } '

This presumes the first line will always be an employee identifier. The for loop is to allow for surnames or multiple given names (Betty Lou, Mary Jo, etc.)

1
  • Really efficient implementation. Commented Sep 19, 2015 at 15:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .