1

I want to use the shell to split this file:

ID: xxx Name: xxx HW = In-class = Comments: ID: yyy Name: yyyy HW = In-class = Comments: ID: zzz Name: Zzzz HW = In-class = Comments: 

So each paragraph is saved to a file named FILE01 which is in a folder that is the ID of the paragraph.

For example paragraph:

ID: zzz Name: Zzzz HW = In-class = Comments: 

Should be saved to the file ./zzz/FILE01.

How can I do this?

5
  • I tried to fix the formatting, please check and edit if needed. Commented Sep 30, 2013 at 19:54
  • By "shell" do you actually mean just the shell, or would you be able to use utils that actually makes sense for this? Commented Sep 30, 2013 at 19:58
  • It because the file is used in linux and I know bash shell a little bit.. Can you make it by some other way? Commented Sep 30, 2013 at 20:02
  • What have you already tried? What should happen if the 'ID' field isn't unique? Are all the field values, limited to a single line or could they occupy more than a single line? Commented Sep 30, 2013 at 20:05
  • "ID" should be unique. The "comments" may have several lines Commented Sep 30, 2013 at 20:07

2 Answers 2

3

try this line pls:

 awk -v RS= '{print > "~/"$2"/FILE01"}' file 

this assumes that those directories (xxx, yyy,zzz) are already there.

Sign up to request clarification or add additional context in comments.

Comments

3

This is quite easy with awk:

$ ls file $ awk '{system("mkdir -p "$2); print > ($2"/FILE01")}' RS= file 

Produces:

$ ls file xxx/ yyy/ zzz/ $ cat xxx/FILE01 ID: xxx Name: xxx HW = In-class = Comments: $ cat yyy/FILE01 ID: yyy Name: yyyy HW = In-class = Comments: $ cat zzz/FILE01 ID: zzz Name: Zzzz HW = In-class = Comments: 

1 Comment

+1 To avoid nasal demons if $2 contains globbing characters, you should quote it, i.e. {system("mkdir -p \""$2"\""); print > ($2"/FILE01")}.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.