Skip to content
Advertisement

In linux system, how to find the words (immediately next alone) next to a given word in a file?

I need to find all the table names alone in all select statements in my query log. Is there any way to grep (or) any other option, to take the strings that comes immediately after the word FROM in my file ..

Example: file contains something like this

select a, b, c FROM `table1` join `table2` etc...
insert into.................
commit
select * FROM `tablex` ..............
select y,s,h FROM `tabley`.................
.
.
. 

Now I want the list of the distinct tables alone from the select stmts. i.e,

table1
tablex
tabley

Advertisement

Answer

I’m not sure if I understand you correctly but if you want to extract the first word that comes after ‘from’ you can try something like this:

➜  tmp cat log 
select id, name from account where name = 'John';
select * from price where id > 0;
➜  tmp cat log | gawk -F'from ' '{print $2}' | gawk '{print $1}'
account
price
➜  tmp 

If you want to print names of joined tables as well you need to extend it.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement