5

I need to copy all lines in a file matching a pattern to a second file.

In detail: I have a sql dump and want to create a second sql file which includes all commands for tables whose name matches dx_postings, dx_postings_archive, and so on. The pattern should be dx_postings.

Any ideas? I'd prefer an awk or sed solution.

ChrJantz
  • 919
  • 1
  • 11
  • 23

3 Answers3

5

The sed solution:

sed -ne '/pattern/ p' infile >outfile
Birei
  • 35,723
  • 2
  • 77
  • 82
2

Ok, see this :

awk '/pattern/' FILE > NEWFILE

more specific :

awk '/^(DROP|LOCK) .*dx_postings/' file.sql > newfile.sql

If you have INSERT or CREATE statements, this is more tricky because there's more than one lines.

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • I want to have all lines matching the pattern in this file, also LOCK INSERT and the CREATE TABLE statements. – ChrJantz Sep 27 '12 at 15:02
  • I want a bear and a pizza. More seriously, consider dumping the DB another one time and add the tables to the command line you'd like to have in the dump. Or consider learning awk. – Gilles Quénot Sep 27 '12 at 15:15
  • Moreover, if you can't dump the DB again, you can create a temporary DB and dumping it then. If you just need to filter a dump for one shot, consider using an editor like `vim`. – Gilles Quénot Sep 27 '12 at 15:18
1

This might work for you (GNU sed);

sed -n '/pattern/w second_file' first_file
potong
  • 55,640
  • 6
  • 51
  • 83