0

I am trying to split a text file into two different files, file looks something like this:

//ABC12//burrito (line of text)
(line of text)
(line of text)
etc
//ABC12//taco (line of text)
(line of text)
(line of text)
etc
//ABC12//taco (line of text)
(line of text)
(line of text)
etc
//ABC12//burrito (line of text)
(line of text)
(line of text)
etc

So I would want to split any line beginning with burrito and all subsuquent lines into a file called burrito until a line with taco in it was read, I think the best way to do this would be:

for each line in $text;
   if line contains burrito
         outputfile=burrito
         line>>$outputfile
   elseif line contains taco
         outputfile=taco
         line>>$outputfile
   else
         line>>$outputfile

but I am not sure, any help would be appreciated.

1
  • fedorqui, thank you for cleaning up my post Commented Dec 30, 2014 at 16:58

2 Answers 2

4

This can be done with awk:

awk '/burrito/ {f="burrito"} /taco/ {f="taco"} {print > f}' file

Explanation

This outputs the lines to a file f, the name of which changes when taco or burrito are found:

  • /burrito/ {f="burrito"} this means: if the line contains burrito, then set the variable f to burrito.
  • /taco/ {f="taco"} the same with taco.
  • {print > f}prints the line into the file stored inf. You can also say{print > f".txt"}` or something else.

If you want to set a default file name, so that it outputs somewhere else until a burrito or taco is found, you can say:

awk 'BEGIN {f="another_file"} /burrito/ {f="burrito"} /taco/ {f="taco"} {print > f}' file
Sign up to request clarification or add additional context in comments.

Comments

2

You can use this awk command:

wk 'BEGIN{split("burrito taco", a); f=a[1]} {
   for (i=1; i<=length(a); i++) if ($0 ~ a[i]) f=a[i]; print $0 > f}' file
  • This will redirect all lines containing taco to a output file called taco
  • This will redirect all lines containing burrito to a output file called burrito
  • Instead of f=a[1] you can initialize the output file name to something else.

1 Comment

Yes after reading the question again I think I misunderstood the requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.