Skip to content
Advertisement

To read desired values from file using linux system commands (grep,awk,sed) [closed]

I have file test.txt contains some variables assigned to some value, i need to read all defined variables for example color = 0;. Basically i am trying to read here is the values which are previous line of parameters()->getParm(” “);

can you please help me out how i can read these values. Also mentioned my expected result.

cat test.txt

   color = 0;
   parameters()->getParm(&color, "-color");
   
   width = 16;
   parameters()->getParm(&width, "-width");

   size = 0;
   parameters()->getParm(&size, "-size");

   species = "Taxon";      
   parameters()->getParm(&species, "-species");

   fly = 100;
   parameters()->getParm(&fly, "-fly");

   swim = 25;
   parameters()->getParm(&swim, "-swim");
 

    expected result:
     color = 0;
     width = 16;
     size = 0;
     species = "Taxon";
     fly = 100;
     swim = 25;

Advertisement

Answer

I would do it following way using GNU AWK, let file.txt content be

   color = 0;
   parameters()->getParm(&color, "-color");
   
   width = 16;
   parameters()->getParm(&width, "-width");

   size = 0;
   parameters()->getParm(&size, "-size");

   species = "Taxon";      
   parameters()->getParm(&species, "-species");

   fly = 100;
   parameters()->getParm(&fly, "-fly");

   swim = 25;
   parameters()->getParm(&swim, "-swim");

then

awk '/parameters()/{print line}{line=$0}' file.txt

output

   color = 0;
   width = 16;
   size = 0;
   species = "Taxon";      
   fly = 100;
   swim = 25;

Explanation: We need to store previous line so we can print it when we find line meeting condition. I use variable name line for storing it, I instructed awk that for each line: if it does contain parameters() print previous line (stored in variable line), always store current line as line. Beware that this solution assumes that line with parameters() will never be first line and relevant line is always immediately before line with parameters().

(tested in gawk 4.2.1)

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