1

Need to separate out lines between two repetitive patterns from an input file and redirect every selection of lines to separate files.

Example Input File Format:
Pattern 1
Line1
Line2
Line3
Pattern 2
Pattern 1
Line4
Line5
Pattern 2

Outoput Files:
File 1:
Pattern 1
Line1
Line2
Line3
Pattern 2

File 2:
Pattern 1
Line4
Line5
Pattern 2

How can this be done as part of shell scripting? I have this following awk command implementation, but it is redirecting the complete output to one file only:
awk '/Pattern\ 1/,/Pattern\ 2/{print > "filename_$var.txt";var=var+1}var' $filename

  • Use print "filename_"var".txt". But you will also have to change the var=var+1 part, or you will get a new file for each match. – Eduardo Trápani Nov 6 '19 at 16:22
  • Yes I do need a new file for each match. But this awk command is giving me the output in one file only – Abhik Dasgupta Nov 6 '19 at 17:46
  • Even with the modification in the first comment? Note that print > "filename_$var.txt" becomes print > "filename_"var".txt" – Eduardo Trápani Nov 6 '19 at 17:51
  • the modification provided in the first comment redirect every line in a separate file. Not the complete chunk in 2 files as provided in the Output Files section – Abhik Dasgupta Nov 7 '19 at 6:54
  • Yes, that's exactly what the first comment says the modification will do. And a hint on how to solve the rest. You will not always get a full answer, or somebody to code your problem. Sometimes you will just receive a (hopefully helpful) piece of information, to keep trying on your own. – Eduardo Trápani Nov 7 '19 at 12:42
0

You can try this:

awk '{if ($0 ~ /Pattern 1/) a++} {print >> "file"a}' file

First awk is looking if the first column is starting with the desired pattern.

If so, the not introduced variable a icrements to a=1.

Second awk appends everything from Pattern 1 to Pattern 2 to the compound string filea as a file.

I hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.