0

I have tried many many times with different tools to extract a pattern from a file using unix tools, but I can't seem to get them to do what I want. So I have a file like this:

[blah]
project=abc123

ON#IRUjdi2ujnq!De

And I want to capture the project name.

I've tried using grep, egrep, awk, and sed, but I haven't been able to get them to work. Here's my current attempt.

cat file | sed -n "s/project = \(.*\)/\1/p"

and here's the current output

abc123

ON#IRUjdi2ujnq!De

For some reason it's considering the last 2 lines to match. I thought my regex would require a literal match on project = but it seems this is not the case.

Can some unix wizard help me out here? Any standard unix tool is fine.

------ EDIT ------

So actually my problem was slightly different. I was actually doing

gcloud config list project | sed -n "s/project = \(.*\)/\1/p"

Sorry I thought that it wouldn't make a difference, but apparently this is the issue.

If you do this gcloud config list project >> file

It will actually only output the the listing of your projects to the file and then it will print

Your active configuration is: [default]

to the terminal, and this is what was messing things up. If I manually write the whole output of doing the gcloud command to a file and then ran sed on that it actually worked. So it's something strange about how gcloud is outputting it's data.

Ryan Stull
  • 1,056
  • 14
  • 35
  • With GNU grep: `grep -Po 'project=\K.*' file` – Cyrus Oct 19 '18 at 21:10
  • Could blocks other than `[blah]` have a `project` key as well? Or is this the only line in the file? I.e., do you want the value of `blah.project`, or just `project`? – Benjamin W. Oct 19 '18 at 21:10
  • @BenjaminW. It's the only one in the file – Ryan Stull Oct 19 '18 at 21:11
  • 1
    `awk -F= '$1=="project"{print $2}' file` – anubhava Oct 19 '18 at 21:13
  • Or similar: https://stackoverflow.com/questions/15148796/get-string-after-character, https://stackoverflow.com/questions/15793452/how-do-i-get-value-of-variable-from-file-using-shell-script – Benjamin W. Oct 19 '18 at 21:14
  • Looks like the issue was the second part of the information was coming over stderr not stdout, which is why it appeared to not be working. Was able to fix it by redirecting stderr to dev/null – Ryan Stull Oct 19 '18 at 21:33

1 Answers1

0

With grep you could do:

grep -o '^project=.*' file | cut -f2- -d=

Result:

abc123
l'L'l
  • 44,951
  • 10
  • 95
  • 146