anika
anika

Reputation: 63

How to get specific string from a file and store it in new file in shell script?

I have one sql file that contain some data in this file some line as follow:

INSERT a=1 , b=2;  
INSERT a=2 , b=10;

like that so many lines are there i want to fetch these lines that contain "INSERT" keyword till semicolon and create a new file and save it into the new file.

using shell script.

Upvotes: 0

Views: 143

Answers (2)

Abdullah
Abdullah

Reputation: 965

cat test.sql 
insert a = 1; b= 2;
delete a, b;
insert d = 8;
insert g = 9;

grep 'insert' test.sql > newfile
cat newfile 
insert a = 1; b= 2;
insert d = 8;
insert g = 9;

This will also help you

^ (caret) means "the beginning of the line". So "^a" means find a line starting with an "a".

$ (dollar sign) means "the end of the line". So "a$" means find a line ending with an "a".

For example, this command searches the file myfile for lines starting with an "s" and ending with an "n", and prints them to the standard output (screen):

cat myfile | grep '^s.*n$'

Upvotes: 0

riteshtch
riteshtch

Reputation: 8769

$ sed -n '/^\s*INSERT/p' data > newfilename
$ cat newfilename 
INSERT a=1 , b=2;
INSERT a=2 , b=10;

or using grep:

$ grep '^INSERT' data > newfilename 
$ cat newfilename 
INSERT a=1 , b=2;
INSERT a=2 , b=10;

Using awk:

$ awk '/^INSERT/' data > newfilename
$ cat newfilename 
INSERT a=1 , b=2;
INSERT a=2 , b=10;

Upvotes: 1

Related Questions