1

I have a huge text file with something like that:

igflex01; igflexdev01; igdbstg01;
igldapint01; igjetdev01; igsql01;
igesxstg01; igdbint01; igdmstg01;
igdsdev01; igdmmmo01; igmsgint02;

and so on...

I would like to extract all text between semicolons when the string 'int' is present. Is there a way to do that?

  • 1
    What would your desired output look like? – Eric Renouf Sep 6 '16 at 18:42
1

Since you asked for sed / grep, here it is:

> cat file
igflex01; igflexdev01; igdbstg01;
igldapint01; igjetdev01; igsql01;
igesxstg01; igdbint01; igdmstg01;
igdsdev01; igdmmmo01; igmsgint02;

> sed -nr 's/\s*;\s*/\n/gp' file | grep int
igldapint01
igdbint01
igmsgint02

Or get it with only a single sed call...

> sed -nr -e 's/\s*;\s*/\n/g;/int/P' file
igldapint01
igdbint01
igmsgint02
2

Used the "tr" command to replace the semicolons with newlines and then run grep (which is line-oriented).

$ cat input.txt | tr ';' '\n' | grep int
 igldapint01
 igdbint01
 igmsgint02
1

One way is to cheat and convert the ; into newlines and then you can just grep eg

tr ';' '\012' | grep int

eg

$ cat x
igflex01; igflexdev01; igdbstg01;
igldapint01; igjetdev01; igsql01;
igesxstg01; igdbint01; igdmstg01;
igdsdev01; igdmmmo01; igmsgint02;

$ cat x | tr ';' '\012' | grep int
igldapint01
 igdbint01
 igmsgint02

Note that it has the spaces in some cases because the space is in between the ;s. Also note that the first word of a line (which isn't strictly between ; on a line, but is between them in the data) is also returned.

0
% echo 'aint;int;cint' | perl -nle 'print for grep /int/, split /\s*;\s*/'
aint
int
cint
% 

Or just split ";" to preserve any whitespace between.

0
$ cat abc.txt 
igflex01; igflexdev01; igdbstg01;
igldapint01; igjetdev01; igsql01;
igesxstg01; igdbint01; igdmstg01;
igdsdev01; igdmmmo01; igmsgint02;

$ grep -o '[^;]*int[^;]*' abc.txt 
igldapint01
 igdbint01
 igmsgint02

If spaces are not desired:

$ grep -o '[^ ;]*int[^ ;]*' abc.txt 
igldapint01
igdbint01
igmsgint02

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.