Home > Software engineering >  Retreive specific values from file
Retreive specific values from file

Time:04-14

I have a file test.cf containing:

   process {

        withName : teq {

            file = "/path/to/teq-0.20.9.txt"

        }

    }

   process {

        withName : cad {

            file = "/path/to/cad-4.0.txt"

        }

    }

   process {

        withName : sik {

            file = "/path/to/sik-20.0.txt"

        }

    }

I would like to retreive value associated at the end of the file for teq, cad and sik

I was first thinking about something like

grep -E 'teq' test.cf

and get only second raw and then remove part of recurrence in line

But it may be easier to do something like:

for a in test.cf
do 
line=$(sed -n '{$a}p' test.cf)

if line=teq
#next line using sed -n?
    do print nextline &> teq.txt
else if line=cad
    do print nextline &> cad.txt
else if line=sik
    do print nextline &> sik.txt
done

(obviously it doesn't work)

EDIT:

output wanted: teq.txt containing teq-0.20.9, cad.txt containing cad-4.0 and sik.txt containing sik-20.0

Is there a good way to do that? Thank you for your comments

CodePudding user response:

Based on your given sample:

awk '/withName/{close(f); f=$3 ".txt"}
     /file/{sub(/.*\//, ""); sub(/\.txt".*/, "");
            print > f}' ip.txt
  • /withName/{close(f); f=$3 ".txt"} if line contains withName, save filename in f using the third field. close() will close any previous file handle
  • /file/{sub(/.*\//, ""); sub(/\.txt".*/, ""); if line contains file, remove everything except the value required
  • print > f print the modified line and redirect to filename in f
    • if you can have multiple entries, use >> instead of >

CodePudding user response:

Here is a solution in awk:

awk '/withName/{name=$3} /file =/{print $3 > name ".txt"}' test.cf
  • /withName/{name=$3}: when I see the line containing "withName", I save that name
  • When I see the line with "file =", I print
  • Related