-1

I am trying to utilize a grep lookahead to get a value at the end of a line for a project I'm working on. The main issue I'm having is that I'm not sure how to use a shell variable in the grep lookahead syntax in cshell

Here's the gist of what I'm trying to do.

There will be a dogfile.txt with several lines listing the names of dogs in the format below

genericDog2033, pomeranian
genericDog2034, greatDane
genericDog2035, Doberman

I wanted a way of retrieving the breed of the dog after the comma on each line so I thought a grep lookahead might be a good way of doing it. The project I'm working on isn't so hard-coded however, so I have no way of knowing what genericDog number I am searching for. There will be a shell variable in a greater while loop which will have access to the dog name.

For example if I set the dogNumber variable to the first dog in the file like so:

set dogNumber = genericDog2033

I then try to access the value of dogNumber in the grep lookahead

set dogBreed = `cat File.txt | grep -oP '(?<=$dogNumber ,)[^ ]*'`

The problem with the line above is that I think grep is looking for the literal string "$dognumber ," in the file which obviously doesn't exist. Is there some sort of wrapper I can put around the shell variable so cshell knows that dogNumber is a variable? I'm also open to other methods of doing this. Any help would be appreciated, this is the literal last line of code I need to finish my project and I'm at my wits end.

OmniMan
  • 1
  • 1

1 Answers1

0

Variable expansion only happens inside double quotes ("), and not single quotes ('):

% set var = 'hello'
% echo '$var'
$var
% echo "$var"
hello

Furthermore, you have an error in your regexp:

(?<=$dogNumber ,)[^ ]*

In your data, the space is after the comma, not before.

% set dogNumber = genericDog2033
% set dogBreed = `cat a | grep -oP "(?<=$dogNumber, )[^ ]*"`
% echo $dogBreed
pomeranian

The easiest way to debug this is to not use variables at all in the first place, and simply check if the grep works:

% grep -oP "(?<=genericDog2034 ,)[^ ].*" a
[no output]

Then first make the grep work with static data, add the variable to make that work, and then put it all together by assigning it to a variable.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146