Reputation: 524
I want to search a pattern in paragraph that begins with CREATE NEW and ends with ";" and print the first line of the paragraph and the line that contains the pattern if the pattern match. for example if I have the following file and I am looking for Lines that begin with FROM
CREATE NEW paragraph num 1
FROM file1
FROM file2
USING file3
;
CREATE NEW paragraph num 2
FROM file2
FROM file6
FROM file5
USING file4
;
the result would be like :
CREATE NEW paragraph num 1 ;FROM file1 ;FROM file2
CREATE NEW paragraph num 2 ;FROM file2 ;FROM file6 ;FROM file5
I managed to print the first line using the answer of the following question how can I find a matching pattern between two words using sed or awk but I don't know how to print the lines that contain the pattern
Upvotes: 2
Views: 852
Reputation: 58473
This might work for you (GNU sed):
ed -nr '/CREATE NEW/,/^;/{/^CREATE NEW/h;/^FROM/H;/^;/!d;g;s/\s*\n/ ;/gp}' file
This collects line beginning CREATE NEW
and containing the lines starting FROM
and replaces the preceeding spaces and newlines with ;
.
Upvotes: 1
Reputation: 659
You can use awk to match the pattern and print matched pattern and line number as follows
BEGIN{
line_num = 0;
print "LineNo : Matched Pattern"
}
{
line = $0
line_num++;
if(line ~ /^CREATE NEW / || $NF==";" || line ~/^FROM /)
print line_num," : " line
}
END
{
}
Upvotes: 0
Reputation: 109
Something like this should work
awk '/CREATE NEW/,/;/ {
if($1=="CREATE")
printf("\n%s ;",$0);
else if($1=="FROM")
printf("%s ;",$0);
}' fileToSearch
Upvotes: 1
Reputation: 785481
Using this awk command:
awk 'p!="" && $0==";"{print p} p!="" && /^FROM /{p = p "; " $0} /^CREATE NEW /{p=$0}' file
CREATE NEW paragraph num 1 ; FROM file1 ; FROM file2
CREATE NEW paragraph num 2 ; FROM file2; FROM file6; FROM file5
Upvotes: 2