1

I have a one line command, lets say

grep needle haystack.file

What if i wanted to replace "needle" with the current working directory using the pwd command. Now it might be possible using pipes but I need the needle part to show the working directory and the rest of the command to be the same.

So preferably something like this:

grep (pwd) haystack.file

Which when executed would actually run the following command:

grep /var/www/html/ haystack.file

I've done a bit of searching and have found a lot of examples with pipes but it cant be applied in my scenario as the first part (grep) and second part (haystack.file) is fixed in an application.

0

2 Answers 2

5

Use the $PWD variable, always set:

grep "$PWD" haystack.file

You can also use command substitution:

grep "$(pwd)" haystack.file

Note the importance of quotes. Do it! Otherwise strange things can happen.

Sign up to request clarification or add additional context in comments.

3 Comments

grep `pwd` haystack.file would work as well, as long as there's no IFS chars in the path.
Yes! Only that I tend not to use ``: they cannot be nested :(
@MarcB It does but there is literally no reason to use `pwd` over "$(pwd)" and many reasons not to.
5

You can use command substitution

Test

$ echo $(pwd) > test
$ grep $(pwd) test
/home/xxx/yyy

OR

$ grep `pwd` test
/home/xxx/yyy

Security

It's always recomended to quote the command substituion to take care of the spaces in the output of pwd command

Test

$ pwd
/home/xxx/yyy/hello world
$(pwd) > test

$ grep $(pwd) test #without quoting
grep: world: No such file or directory
test:/home/xxx/yyy/hello world

$ grep "$(pwd)" test #with quoting
/home/xxx/yyy/hello world

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.