Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

file.txt contains:

aa=testing
sss=whoiam
bbb=findme

What command do I use to search for testing and print it?

Expected result:

# you search testing
share|improve this question

1 Answer 1

You could use grep:

string=testing && grep "$string" file.txt 2>&1 >/dev/null && echo "you search $string"

The string "you search testing" is printed when the string "testing" is found somewhere in the file file.txt.

  • string=testing: set the variable $string
  • grep "$string" file.txt 2>&1 >/dev/null: grep searches for the string in the file. We don't want the output that because both (stdin and stderr) are redirected to /dev/null.
  • echo "you search $string": if everything is succesfull, print the string.

Just change the variable $string for your pattern.

Additional quesitions:

how about if i want to search the value for aa?

With this oneliner the value of aa is search too. The complete content of the file file.txt is gone trough.

i mean my reference is aa not its value(testing)?

Use this:

string=aa && grep "^$string=" file.txt | awk -F= '{printf "you search %s\n", $2}'

This searched for aa as variable name and then prints the value. The output od this would be:

you search testing
share|improve this answer
1  
What is the point of using export? –  Bernhard Aug 15 '14 at 7:15
    
@Bernhard true, I see. It's not needed to make it an environment variable. Edited, tanks. –  chaos Aug 15 '14 at 8:21
    
By using grep's -q flag (for 'quiet) mayou can make the oneliner even simpler: string=testing && grep -q "$string" file.txt && echo "you search $string"` –  ph0t0nix Aug 19 '14 at 14:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.