1

Suppose I have a file in which there are lines matching same pattern but under different blocks how to write them in a separate file using grep/awk for example:

$ cat file.txt
spin 1 
voltage current
spin 2
voltage current
$

I want to write spin 1 voltage current in a separate file "spi1.dat" and spin 2 voltage current in a separate file. How to I do this using grep/awk?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Acharya
  • 11
  • 2
  • Possible duplicate of [Using regex to tell csplit where to split the file](http://stackoverflow.com/questions/18364411/using-regex-to-tell-csplit-where-to-split-the-file) – tripleee Nov 25 '15 at 07:45
  • 1
    Do you want to look for lines that start with "spin" and print everything after them into one file, or look for lines that start with "voltage" and print them to a file named based on the last line that didn't start with voltage or something else? – Ed Morton Nov 25 '15 at 14:52

3 Answers3

0

No idea with awk but you can do a somewhat similar thing with split:

split -d -l 2 file.txt spi.dat
Xavier Nayrac
  • 530
  • 5
  • 16
0

In grep -A option is used to Print lines of trailing context after matching.

  grep 'spin 1' -A1  file.txt spi1.dat
loganaayahee
  • 809
  • 2
  • 8
  • 13
0

Not quite clear but here's an awk approach:

awk '/^spin/{spin=$0;idx=$NF;getline;print spin" "$0 >"spin"idx".dat"}' infile
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52