Difference in two types of command that uses grepgrep command not returning all resultsIs grep syntax different from regex?Why does the more command not work when bound to a keyboard shortcut?proper syntax for grep: search a string, copy two rows above and transposePrint a specific part in an outputgrep invert not working the way I expectedprint a string from a specific fileHow to grep for two patterns in multiple files“ls | grep zip” vs. “grep zip $(ls)”

Scientific Illustration: Non-photorealistic rendering of sparse wireframe with dashed/dotted lines for backfacing areas - Blender 2.80

How can I justify this without determining the determinant?

How do you call a note, that stays through the whole song?

Why are branches relative in many 8-bit CPUs?

Is there a theory challenging the "strict" distinction between Thai and Vietnamese?

What does ゴン part in イノゴン mean?

Best fighting style for a pacifist

What was Jeremy Corbyn’s involvement in the Northern Ireland peace process?

Can the diameter be controled by the injectivity radius and the volume?

Variadic templates: unfold arguments in groups

Are there any exemplars of the 'trope of the exiled poet' prior to CE 8?

Rip secret door, showing no trace of edges, into shade smooth sphere

Old short about robots searching for the "Great Enemy" that wiped out mankind

Is there no way in Windows 10 to type the Euro symbol € on a US English keyboard that has neither numeric keypad nor "alt gr" key?

Banking system in C++

Short story about delivery truck organization existing only to support itself

Alternative to IrfanView

Why did we never simplify key signatures?

Sue newspaper or the reporter for libel?

How often are there lunar eclipses on Jupiter

How does "unlimited holidays" work in practice?

What is the rationale for single engine military aircraft?

What is the difference between "cat < filename" and "cat filename"?

Can the Fortress spell be dispelled?



Difference in two types of command that uses grep


grep command not returning all resultsIs grep syntax different from regex?Why does the more command not work when bound to a keyboard shortcut?proper syntax for grep: search a string, copy two rows above and transposePrint a specific part in an outputgrep invert not working the way I expectedprint a string from a specific fileHow to grep for two patterns in multiple files“ls | grep zip” vs. “grep zip $(ls)”






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









5


















So, here we have two commands:



cat /var/log/dpkg.log | grep " install "
cat /var/log/dpkg.log | grep install


Why are the outputs of these commands different? And can you please explain the first command a little. Thank you in advance.










share|improve this question






















  • 3





    Can it be that the first one has a typo and was meant to look like that? cat /var/log/dpkg.log | grep " install " (position of the first backslash!)

    – Byte Commander
    Dec 21 '15 at 16:30











  • @ByteCommander - Both seems to show the same output.

    – Raphael
    Dec 21 '15 at 16:32






  • 2





    The first slash of the first command does not make much sense. It escapes i, which does not have any special meaning anyway, so it is equivalent to grep " install ".

    – fedorqui
    Dec 21 '15 at 17:12






  • 3





    and backslash-space wouldn't have any special meaning either, so it's the difference between grep " install " (with spaces) and grep install (without)

    – glenn jackman
    Dec 21 '15 at 17:39

















5


















So, here we have two commands:



cat /var/log/dpkg.log | grep " install "
cat /var/log/dpkg.log | grep install


Why are the outputs of these commands different? And can you please explain the first command a little. Thank you in advance.










share|improve this question






















  • 3





    Can it be that the first one has a typo and was meant to look like that? cat /var/log/dpkg.log | grep " install " (position of the first backslash!)

    – Byte Commander
    Dec 21 '15 at 16:30











  • @ByteCommander - Both seems to show the same output.

    – Raphael
    Dec 21 '15 at 16:32






  • 2





    The first slash of the first command does not make much sense. It escapes i, which does not have any special meaning anyway, so it is equivalent to grep " install ".

    – fedorqui
    Dec 21 '15 at 17:12






  • 3





    and backslash-space wouldn't have any special meaning either, so it's the difference between grep " install " (with spaces) and grep install (without)

    – glenn jackman
    Dec 21 '15 at 17:39













5













5









5


1






So, here we have two commands:



cat /var/log/dpkg.log | grep " install "
cat /var/log/dpkg.log | grep install


Why are the outputs of these commands different? And can you please explain the first command a little. Thank you in advance.










share|improve this question
















So, here we have two commands:



cat /var/log/dpkg.log | grep " install "
cat /var/log/dpkg.log | grep install


Why are the outputs of these commands different? And can you please explain the first command a little. Thank you in advance.







command-line grep






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 22 '15 at 13:42









chaos

21.1k8 gold badges62 silver badges69 bronze badges




21.1k8 gold badges62 silver badges69 bronze badges










asked Dec 21 '15 at 16:25









RaphaelRaphael

6,7173 gold badges22 silver badges44 bronze badges




6,7173 gold badges22 silver badges44 bronze badges










  • 3





    Can it be that the first one has a typo and was meant to look like that? cat /var/log/dpkg.log | grep " install " (position of the first backslash!)

    – Byte Commander
    Dec 21 '15 at 16:30











  • @ByteCommander - Both seems to show the same output.

    – Raphael
    Dec 21 '15 at 16:32






  • 2





    The first slash of the first command does not make much sense. It escapes i, which does not have any special meaning anyway, so it is equivalent to grep " install ".

    – fedorqui
    Dec 21 '15 at 17:12






  • 3





    and backslash-space wouldn't have any special meaning either, so it's the difference between grep " install " (with spaces) and grep install (without)

    – glenn jackman
    Dec 21 '15 at 17:39












  • 3





    Can it be that the first one has a typo and was meant to look like that? cat /var/log/dpkg.log | grep " install " (position of the first backslash!)

    – Byte Commander
    Dec 21 '15 at 16:30











  • @ByteCommander - Both seems to show the same output.

    – Raphael
    Dec 21 '15 at 16:32






  • 2





    The first slash of the first command does not make much sense. It escapes i, which does not have any special meaning anyway, so it is equivalent to grep " install ".

    – fedorqui
    Dec 21 '15 at 17:12






  • 3





    and backslash-space wouldn't have any special meaning either, so it's the difference between grep " install " (with spaces) and grep install (without)

    – glenn jackman
    Dec 21 '15 at 17:39







3




3





Can it be that the first one has a typo and was meant to look like that? cat /var/log/dpkg.log | grep " install " (position of the first backslash!)

– Byte Commander
Dec 21 '15 at 16:30





Can it be that the first one has a typo and was meant to look like that? cat /var/log/dpkg.log | grep " install " (position of the first backslash!)

– Byte Commander
Dec 21 '15 at 16:30













@ByteCommander - Both seems to show the same output.

– Raphael
Dec 21 '15 at 16:32





@ByteCommander - Both seems to show the same output.

– Raphael
Dec 21 '15 at 16:32




2




2





The first slash of the first command does not make much sense. It escapes i, which does not have any special meaning anyway, so it is equivalent to grep " install ".

– fedorqui
Dec 21 '15 at 17:12





The first slash of the first command does not make much sense. It escapes i, which does not have any special meaning anyway, so it is equivalent to grep " install ".

– fedorqui
Dec 21 '15 at 17:12




3




3





and backslash-space wouldn't have any special meaning either, so it's the difference between grep " install " (with spaces) and grep install (without)

– glenn jackman
Dec 21 '15 at 17:39





and backslash-space wouldn't have any special meaning either, so it's the difference between grep " install " (with spaces) and grep install (without)

– glenn jackman
Dec 21 '15 at 17:39










3 Answers
3






active

oldest

votes


















8



















The first part of your two commands (cat FILENAME) is always the same and just prints the specified file's content to the STDOUT stream. I will not explain it any further.



The point of our interest is the grep part.



Syntax of grep:



grep [OPTIONS] PATTERN [FILE...]


You can pass grep some options to tweak its behaviour (e.g set the used RegEx flavour or control the output formatting), but those are not used in your case.



The next single argument must be the pattern to match, where a regular expression ("RegEx") or a fixed string (if grep is called with the -F option) is required. In your example, this is the install or " install " part. I will explain it in the next paragraph.



After that, you specify the source of the data to match. This can either be a file name, or nothing. In the second case, grep will read from the STDIN stream (standard input: normally what you type with the keyboard), where you pipe (|) the output from the previous command.



How to correctly pass the "PATTERN" argument?



The pattern parameter must be a single argument. That means, you can't just pass several words or anything containing spaces or shell special characters here, because spaces are treated as argument separators in Bash and probably every other shell as well, and shell special characters such as ; will break the command.



But you have two options to include spaces into the pattern to match anyway:



  • Put the entire string to match in single ('...') or double ("...") quotes. This way, the shell parses the entire quotes-enclosed string as one argument and passes it on to grep.


  • Escape every space in the pattern with a backslash (). That means, you write a backslash before every space which you don't want to be seen as argument separator by the shell. But note that if you want to have an actual backslash in the pattern, you must escape it as well, by writing another backslash before it.


If we now analyse the difference of your two grep command examples, we see the difference in what they match:



cat /var/log/dpkg.log | grep " install "


This matches the pattern install. (Note the leading and trailing space!)



Here we see both methods: double quotes around the entire pattern and backslash-escaping the spaces inside it. It's superfluous to be honest, one would have been enough. Although it doesn't hurt in this case, you should not do this and decide on one method. Usually I would recommend to use quotation marks, as it's easier to read.



cat /var/log/dpkg.log | grep install


This matches the pattern install. (No surrounding spaces.)



Here the pattern only consists of the word install, nothing else. No spaces.



Difference between your commands:



As I said, the first of your examples only matches the word install when it is surrounded by spaces. It would not match if e.g. there's a full stop or any other character directly before or after it instead. It would also not match the word directly at the beginning or end of a line.



The second example does not care about any spaces before or after the word install. It also matches at line beginnings and endings as well as if it is surrounded by any punctuation. It even matches if there is a word containing this letter sequence anywhere, e.g. "uninstall", "reinstall" or "installation" too!



Example with correct/useful backslash escaping:



As in the example you provided the backslashes are superfluous, here the same example without quotes, but with backslash escaping only instead:



cat /var/log/dpkg.log | grep install 


Or if you want to match the string "I like Ubuntu" in a file /home/you/path with spaces/textfile without using quotes, you would do that like this:



grep I like Ubuntu /home/you/path with spaces/textfile


You see that you must escape spaces in path- or filenames as well - or quote them. The line above is equal to the line below:



grep "I like Ubuntu" "/home/you/path with spaces/textfile"





share|improve this answer




























  • There is just one more question. Can you please show another example that shows use of backlash?

    – Raphael
    Dec 21 '15 at 17:42











  • Done. See my last paragraph, please.

    – Byte Commander
    Dec 21 '15 at 17:49











  • Thanx Byte, you are awesome!

    – Raphael
    Dec 21 '15 at 17:51


















4



















The second (simpler) form will match the given string anywhere in a line: so for example it will match strings like installation, re-install, installed etc.



The first expression will only match install where it has a space at each end. The backslashes are something of a red herring since the quotes are already enough (and the first one - needlessly - escapes the i rather than the space): however it could have been written using just backslash escapes as



cat /var/log/dpkg.log | grep install 


(NB there is a literal space character at the end of the above command).




Adding a single space to the pattern is a bit of a hack IMHO: it won't work if the pattern is separated by other whitespace (tabs or line endings). A better option might be to use explicit word boundaries e.g.



grep 'binstallb' /var/log/dpkg.log


or use the -w (--word-regexp) switch



grep -w 'install' /var/log/dpkg.log


(although these include hyphens as well as whitespace - so the equivalence isn't exact). If you really want whitespace separated instances of the pattern, then you can use the [[:space:]] POSIX character class e.g.



grep '[[:space:]]install[[:space:]]' /var/log/dpkg.log





share|improve this answer

































    3



















    The first command:



    cat /var/log/dpkg.log | grep " install "


    As @ByteCommander pointed out, there may be a typo and the command should be



    cat /var/log/dpkg.log | grep " install "


    This would match the string install with a trailing and a leading whitespace. This could also be achieved by using grep -w "install". Also, the is not needed, when you use quotes.



    The second command:



    cat /var/log/dpkg.log | grep install


    This command also matches strings, that contain install. For example "installed".




    Test Case:

    content of testfile:



    foo
    bar
    foobar
    foo bar


    Run:



    cat file1.txt | grep foo
    foo
    foobar
    foo bar

    cat file1.txt | grep -w foo
    foo
    foo bar

    cat file1.txt | grep "foo "
    foo bar





    share|improve this answer



























      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "89"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );














      draft saved

      draft discarded
















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f712025%2fdifference-in-two-types-of-command-that-uses-grep%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown


























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      8



















      The first part of your two commands (cat FILENAME) is always the same and just prints the specified file's content to the STDOUT stream. I will not explain it any further.



      The point of our interest is the grep part.



      Syntax of grep:



      grep [OPTIONS] PATTERN [FILE...]


      You can pass grep some options to tweak its behaviour (e.g set the used RegEx flavour or control the output formatting), but those are not used in your case.



      The next single argument must be the pattern to match, where a regular expression ("RegEx") or a fixed string (if grep is called with the -F option) is required. In your example, this is the install or " install " part. I will explain it in the next paragraph.



      After that, you specify the source of the data to match. This can either be a file name, or nothing. In the second case, grep will read from the STDIN stream (standard input: normally what you type with the keyboard), where you pipe (|) the output from the previous command.



      How to correctly pass the "PATTERN" argument?



      The pattern parameter must be a single argument. That means, you can't just pass several words or anything containing spaces or shell special characters here, because spaces are treated as argument separators in Bash and probably every other shell as well, and shell special characters such as ; will break the command.



      But you have two options to include spaces into the pattern to match anyway:



      • Put the entire string to match in single ('...') or double ("...") quotes. This way, the shell parses the entire quotes-enclosed string as one argument and passes it on to grep.


      • Escape every space in the pattern with a backslash (). That means, you write a backslash before every space which you don't want to be seen as argument separator by the shell. But note that if you want to have an actual backslash in the pattern, you must escape it as well, by writing another backslash before it.


      If we now analyse the difference of your two grep command examples, we see the difference in what they match:



      cat /var/log/dpkg.log | grep " install "


      This matches the pattern install. (Note the leading and trailing space!)



      Here we see both methods: double quotes around the entire pattern and backslash-escaping the spaces inside it. It's superfluous to be honest, one would have been enough. Although it doesn't hurt in this case, you should not do this and decide on one method. Usually I would recommend to use quotation marks, as it's easier to read.



      cat /var/log/dpkg.log | grep install


      This matches the pattern install. (No surrounding spaces.)



      Here the pattern only consists of the word install, nothing else. No spaces.



      Difference between your commands:



      As I said, the first of your examples only matches the word install when it is surrounded by spaces. It would not match if e.g. there's a full stop or any other character directly before or after it instead. It would also not match the word directly at the beginning or end of a line.



      The second example does not care about any spaces before or after the word install. It also matches at line beginnings and endings as well as if it is surrounded by any punctuation. It even matches if there is a word containing this letter sequence anywhere, e.g. "uninstall", "reinstall" or "installation" too!



      Example with correct/useful backslash escaping:



      As in the example you provided the backslashes are superfluous, here the same example without quotes, but with backslash escaping only instead:



      cat /var/log/dpkg.log | grep install 


      Or if you want to match the string "I like Ubuntu" in a file /home/you/path with spaces/textfile without using quotes, you would do that like this:



      grep I like Ubuntu /home/you/path with spaces/textfile


      You see that you must escape spaces in path- or filenames as well - or quote them. The line above is equal to the line below:



      grep "I like Ubuntu" "/home/you/path with spaces/textfile"





      share|improve this answer




























      • There is just one more question. Can you please show another example that shows use of backlash?

        – Raphael
        Dec 21 '15 at 17:42











      • Done. See my last paragraph, please.

        – Byte Commander
        Dec 21 '15 at 17:49











      • Thanx Byte, you are awesome!

        – Raphael
        Dec 21 '15 at 17:51















      8



















      The first part of your two commands (cat FILENAME) is always the same and just prints the specified file's content to the STDOUT stream. I will not explain it any further.



      The point of our interest is the grep part.



      Syntax of grep:



      grep [OPTIONS] PATTERN [FILE...]


      You can pass grep some options to tweak its behaviour (e.g set the used RegEx flavour or control the output formatting), but those are not used in your case.



      The next single argument must be the pattern to match, where a regular expression ("RegEx") or a fixed string (if grep is called with the -F option) is required. In your example, this is the install or " install " part. I will explain it in the next paragraph.



      After that, you specify the source of the data to match. This can either be a file name, or nothing. In the second case, grep will read from the STDIN stream (standard input: normally what you type with the keyboard), where you pipe (|) the output from the previous command.



      How to correctly pass the "PATTERN" argument?



      The pattern parameter must be a single argument. That means, you can't just pass several words or anything containing spaces or shell special characters here, because spaces are treated as argument separators in Bash and probably every other shell as well, and shell special characters such as ; will break the command.



      But you have two options to include spaces into the pattern to match anyway:



      • Put the entire string to match in single ('...') or double ("...") quotes. This way, the shell parses the entire quotes-enclosed string as one argument and passes it on to grep.


      • Escape every space in the pattern with a backslash (). That means, you write a backslash before every space which you don't want to be seen as argument separator by the shell. But note that if you want to have an actual backslash in the pattern, you must escape it as well, by writing another backslash before it.


      If we now analyse the difference of your two grep command examples, we see the difference in what they match:



      cat /var/log/dpkg.log | grep " install "


      This matches the pattern install. (Note the leading and trailing space!)



      Here we see both methods: double quotes around the entire pattern and backslash-escaping the spaces inside it. It's superfluous to be honest, one would have been enough. Although it doesn't hurt in this case, you should not do this and decide on one method. Usually I would recommend to use quotation marks, as it's easier to read.



      cat /var/log/dpkg.log | grep install


      This matches the pattern install. (No surrounding spaces.)



      Here the pattern only consists of the word install, nothing else. No spaces.



      Difference between your commands:



      As I said, the first of your examples only matches the word install when it is surrounded by spaces. It would not match if e.g. there's a full stop or any other character directly before or after it instead. It would also not match the word directly at the beginning or end of a line.



      The second example does not care about any spaces before or after the word install. It also matches at line beginnings and endings as well as if it is surrounded by any punctuation. It even matches if there is a word containing this letter sequence anywhere, e.g. "uninstall", "reinstall" or "installation" too!



      Example with correct/useful backslash escaping:



      As in the example you provided the backslashes are superfluous, here the same example without quotes, but with backslash escaping only instead:



      cat /var/log/dpkg.log | grep install 


      Or if you want to match the string "I like Ubuntu" in a file /home/you/path with spaces/textfile without using quotes, you would do that like this:



      grep I like Ubuntu /home/you/path with spaces/textfile


      You see that you must escape spaces in path- or filenames as well - or quote them. The line above is equal to the line below:



      grep "I like Ubuntu" "/home/you/path with spaces/textfile"





      share|improve this answer




























      • There is just one more question. Can you please show another example that shows use of backlash?

        – Raphael
        Dec 21 '15 at 17:42











      • Done. See my last paragraph, please.

        – Byte Commander
        Dec 21 '15 at 17:49











      • Thanx Byte, you are awesome!

        – Raphael
        Dec 21 '15 at 17:51













      8















      8











      8









      The first part of your two commands (cat FILENAME) is always the same and just prints the specified file's content to the STDOUT stream. I will not explain it any further.



      The point of our interest is the grep part.



      Syntax of grep:



      grep [OPTIONS] PATTERN [FILE...]


      You can pass grep some options to tweak its behaviour (e.g set the used RegEx flavour or control the output formatting), but those are not used in your case.



      The next single argument must be the pattern to match, where a regular expression ("RegEx") or a fixed string (if grep is called with the -F option) is required. In your example, this is the install or " install " part. I will explain it in the next paragraph.



      After that, you specify the source of the data to match. This can either be a file name, or nothing. In the second case, grep will read from the STDIN stream (standard input: normally what you type with the keyboard), where you pipe (|) the output from the previous command.



      How to correctly pass the "PATTERN" argument?



      The pattern parameter must be a single argument. That means, you can't just pass several words or anything containing spaces or shell special characters here, because spaces are treated as argument separators in Bash and probably every other shell as well, and shell special characters such as ; will break the command.



      But you have two options to include spaces into the pattern to match anyway:



      • Put the entire string to match in single ('...') or double ("...") quotes. This way, the shell parses the entire quotes-enclosed string as one argument and passes it on to grep.


      • Escape every space in the pattern with a backslash (). That means, you write a backslash before every space which you don't want to be seen as argument separator by the shell. But note that if you want to have an actual backslash in the pattern, you must escape it as well, by writing another backslash before it.


      If we now analyse the difference of your two grep command examples, we see the difference in what they match:



      cat /var/log/dpkg.log | grep " install "


      This matches the pattern install. (Note the leading and trailing space!)



      Here we see both methods: double quotes around the entire pattern and backslash-escaping the spaces inside it. It's superfluous to be honest, one would have been enough. Although it doesn't hurt in this case, you should not do this and decide on one method. Usually I would recommend to use quotation marks, as it's easier to read.



      cat /var/log/dpkg.log | grep install


      This matches the pattern install. (No surrounding spaces.)



      Here the pattern only consists of the word install, nothing else. No spaces.



      Difference between your commands:



      As I said, the first of your examples only matches the word install when it is surrounded by spaces. It would not match if e.g. there's a full stop or any other character directly before or after it instead. It would also not match the word directly at the beginning or end of a line.



      The second example does not care about any spaces before or after the word install. It also matches at line beginnings and endings as well as if it is surrounded by any punctuation. It even matches if there is a word containing this letter sequence anywhere, e.g. "uninstall", "reinstall" or "installation" too!



      Example with correct/useful backslash escaping:



      As in the example you provided the backslashes are superfluous, here the same example without quotes, but with backslash escaping only instead:



      cat /var/log/dpkg.log | grep install 


      Or if you want to match the string "I like Ubuntu" in a file /home/you/path with spaces/textfile without using quotes, you would do that like this:



      grep I like Ubuntu /home/you/path with spaces/textfile


      You see that you must escape spaces in path- or filenames as well - or quote them. The line above is equal to the line below:



      grep "I like Ubuntu" "/home/you/path with spaces/textfile"





      share|improve this answer
















      The first part of your two commands (cat FILENAME) is always the same and just prints the specified file's content to the STDOUT stream. I will not explain it any further.



      The point of our interest is the grep part.



      Syntax of grep:



      grep [OPTIONS] PATTERN [FILE...]


      You can pass grep some options to tweak its behaviour (e.g set the used RegEx flavour or control the output formatting), but those are not used in your case.



      The next single argument must be the pattern to match, where a regular expression ("RegEx") or a fixed string (if grep is called with the -F option) is required. In your example, this is the install or " install " part. I will explain it in the next paragraph.



      After that, you specify the source of the data to match. This can either be a file name, or nothing. In the second case, grep will read from the STDIN stream (standard input: normally what you type with the keyboard), where you pipe (|) the output from the previous command.



      How to correctly pass the "PATTERN" argument?



      The pattern parameter must be a single argument. That means, you can't just pass several words or anything containing spaces or shell special characters here, because spaces are treated as argument separators in Bash and probably every other shell as well, and shell special characters such as ; will break the command.



      But you have two options to include spaces into the pattern to match anyway:



      • Put the entire string to match in single ('...') or double ("...") quotes. This way, the shell parses the entire quotes-enclosed string as one argument and passes it on to grep.


      • Escape every space in the pattern with a backslash (). That means, you write a backslash before every space which you don't want to be seen as argument separator by the shell. But note that if you want to have an actual backslash in the pattern, you must escape it as well, by writing another backslash before it.


      If we now analyse the difference of your two grep command examples, we see the difference in what they match:



      cat /var/log/dpkg.log | grep " install "


      This matches the pattern install. (Note the leading and trailing space!)



      Here we see both methods: double quotes around the entire pattern and backslash-escaping the spaces inside it. It's superfluous to be honest, one would have been enough. Although it doesn't hurt in this case, you should not do this and decide on one method. Usually I would recommend to use quotation marks, as it's easier to read.



      cat /var/log/dpkg.log | grep install


      This matches the pattern install. (No surrounding spaces.)



      Here the pattern only consists of the word install, nothing else. No spaces.



      Difference between your commands:



      As I said, the first of your examples only matches the word install when it is surrounded by spaces. It would not match if e.g. there's a full stop or any other character directly before or after it instead. It would also not match the word directly at the beginning or end of a line.



      The second example does not care about any spaces before or after the word install. It also matches at line beginnings and endings as well as if it is surrounded by any punctuation. It even matches if there is a word containing this letter sequence anywhere, e.g. "uninstall", "reinstall" or "installation" too!



      Example with correct/useful backslash escaping:



      As in the example you provided the backslashes are superfluous, here the same example without quotes, but with backslash escaping only instead:



      cat /var/log/dpkg.log | grep install 


      Or if you want to match the string "I like Ubuntu" in a file /home/you/path with spaces/textfile without using quotes, you would do that like this:



      grep I like Ubuntu /home/you/path with spaces/textfile


      You see that you must escape spaces in path- or filenames as well - or quote them. The line above is equal to the line below:



      grep "I like Ubuntu" "/home/you/path with spaces/textfile"






      share|improve this answer















      share|improve this answer




      share|improve this answer








      edited Dec 21 '15 at 18:57









      kos

      28.3k9 gold badges73 silver badges128 bronze badges




      28.3k9 gold badges73 silver badges128 bronze badges










      answered Dec 21 '15 at 17:09









      Byte CommanderByte Commander

      80.1k30 gold badges198 silver badges342 bronze badges




      80.1k30 gold badges198 silver badges342 bronze badges















      • There is just one more question. Can you please show another example that shows use of backlash?

        – Raphael
        Dec 21 '15 at 17:42











      • Done. See my last paragraph, please.

        – Byte Commander
        Dec 21 '15 at 17:49











      • Thanx Byte, you are awesome!

        – Raphael
        Dec 21 '15 at 17:51

















      • There is just one more question. Can you please show another example that shows use of backlash?

        – Raphael
        Dec 21 '15 at 17:42











      • Done. See my last paragraph, please.

        – Byte Commander
        Dec 21 '15 at 17:49











      • Thanx Byte, you are awesome!

        – Raphael
        Dec 21 '15 at 17:51
















      There is just one more question. Can you please show another example that shows use of backlash?

      – Raphael
      Dec 21 '15 at 17:42





      There is just one more question. Can you please show another example that shows use of backlash?

      – Raphael
      Dec 21 '15 at 17:42













      Done. See my last paragraph, please.

      – Byte Commander
      Dec 21 '15 at 17:49





      Done. See my last paragraph, please.

      – Byte Commander
      Dec 21 '15 at 17:49













      Thanx Byte, you are awesome!

      – Raphael
      Dec 21 '15 at 17:51





      Thanx Byte, you are awesome!

      – Raphael
      Dec 21 '15 at 17:51













      4



















      The second (simpler) form will match the given string anywhere in a line: so for example it will match strings like installation, re-install, installed etc.



      The first expression will only match install where it has a space at each end. The backslashes are something of a red herring since the quotes are already enough (and the first one - needlessly - escapes the i rather than the space): however it could have been written using just backslash escapes as



      cat /var/log/dpkg.log | grep install 


      (NB there is a literal space character at the end of the above command).




      Adding a single space to the pattern is a bit of a hack IMHO: it won't work if the pattern is separated by other whitespace (tabs or line endings). A better option might be to use explicit word boundaries e.g.



      grep 'binstallb' /var/log/dpkg.log


      or use the -w (--word-regexp) switch



      grep -w 'install' /var/log/dpkg.log


      (although these include hyphens as well as whitespace - so the equivalence isn't exact). If you really want whitespace separated instances of the pattern, then you can use the [[:space:]] POSIX character class e.g.



      grep '[[:space:]]install[[:space:]]' /var/log/dpkg.log





      share|improve this answer






























        4



















        The second (simpler) form will match the given string anywhere in a line: so for example it will match strings like installation, re-install, installed etc.



        The first expression will only match install where it has a space at each end. The backslashes are something of a red herring since the quotes are already enough (and the first one - needlessly - escapes the i rather than the space): however it could have been written using just backslash escapes as



        cat /var/log/dpkg.log | grep install 


        (NB there is a literal space character at the end of the above command).




        Adding a single space to the pattern is a bit of a hack IMHO: it won't work if the pattern is separated by other whitespace (tabs or line endings). A better option might be to use explicit word boundaries e.g.



        grep 'binstallb' /var/log/dpkg.log


        or use the -w (--word-regexp) switch



        grep -w 'install' /var/log/dpkg.log


        (although these include hyphens as well as whitespace - so the equivalence isn't exact). If you really want whitespace separated instances of the pattern, then you can use the [[:space:]] POSIX character class e.g.



        grep '[[:space:]]install[[:space:]]' /var/log/dpkg.log





        share|improve this answer




























          4















          4











          4









          The second (simpler) form will match the given string anywhere in a line: so for example it will match strings like installation, re-install, installed etc.



          The first expression will only match install where it has a space at each end. The backslashes are something of a red herring since the quotes are already enough (and the first one - needlessly - escapes the i rather than the space): however it could have been written using just backslash escapes as



          cat /var/log/dpkg.log | grep install 


          (NB there is a literal space character at the end of the above command).




          Adding a single space to the pattern is a bit of a hack IMHO: it won't work if the pattern is separated by other whitespace (tabs or line endings). A better option might be to use explicit word boundaries e.g.



          grep 'binstallb' /var/log/dpkg.log


          or use the -w (--word-regexp) switch



          grep -w 'install' /var/log/dpkg.log


          (although these include hyphens as well as whitespace - so the equivalence isn't exact). If you really want whitespace separated instances of the pattern, then you can use the [[:space:]] POSIX character class e.g.



          grep '[[:space:]]install[[:space:]]' /var/log/dpkg.log





          share|improve this answer














          The second (simpler) form will match the given string anywhere in a line: so for example it will match strings like installation, re-install, installed etc.



          The first expression will only match install where it has a space at each end. The backslashes are something of a red herring since the quotes are already enough (and the first one - needlessly - escapes the i rather than the space): however it could have been written using just backslash escapes as



          cat /var/log/dpkg.log | grep install 


          (NB there is a literal space character at the end of the above command).




          Adding a single space to the pattern is a bit of a hack IMHO: it won't work if the pattern is separated by other whitespace (tabs or line endings). A better option might be to use explicit word boundaries e.g.



          grep 'binstallb' /var/log/dpkg.log


          or use the -w (--word-regexp) switch



          grep -w 'install' /var/log/dpkg.log


          (although these include hyphens as well as whitespace - so the equivalence isn't exact). If you really want whitespace separated instances of the pattern, then you can use the [[:space:]] POSIX character class e.g.



          grep '[[:space:]]install[[:space:]]' /var/log/dpkg.log






          share|improve this answer













          share|improve this answer




          share|improve this answer










          answered Dec 21 '15 at 17:07









          steeldriversteeldriver

          82.1k12 gold badges133 silver badges222 bronze badges




          82.1k12 gold badges133 silver badges222 bronze badges
























              3



















              The first command:



              cat /var/log/dpkg.log | grep " install "


              As @ByteCommander pointed out, there may be a typo and the command should be



              cat /var/log/dpkg.log | grep " install "


              This would match the string install with a trailing and a leading whitespace. This could also be achieved by using grep -w "install". Also, the is not needed, when you use quotes.



              The second command:



              cat /var/log/dpkg.log | grep install


              This command also matches strings, that contain install. For example "installed".




              Test Case:

              content of testfile:



              foo
              bar
              foobar
              foo bar


              Run:



              cat file1.txt | grep foo
              foo
              foobar
              foo bar

              cat file1.txt | grep -w foo
              foo
              foo bar

              cat file1.txt | grep "foo "
              foo bar





              share|improve this answer






























                3



















                The first command:



                cat /var/log/dpkg.log | grep " install "


                As @ByteCommander pointed out, there may be a typo and the command should be



                cat /var/log/dpkg.log | grep " install "


                This would match the string install with a trailing and a leading whitespace. This could also be achieved by using grep -w "install". Also, the is not needed, when you use quotes.



                The second command:



                cat /var/log/dpkg.log | grep install


                This command also matches strings, that contain install. For example "installed".




                Test Case:

                content of testfile:



                foo
                bar
                foobar
                foo bar


                Run:



                cat file1.txt | grep foo
                foo
                foobar
                foo bar

                cat file1.txt | grep -w foo
                foo
                foo bar

                cat file1.txt | grep "foo "
                foo bar





                share|improve this answer




























                  3















                  3











                  3









                  The first command:



                  cat /var/log/dpkg.log | grep " install "


                  As @ByteCommander pointed out, there may be a typo and the command should be



                  cat /var/log/dpkg.log | grep " install "


                  This would match the string install with a trailing and a leading whitespace. This could also be achieved by using grep -w "install". Also, the is not needed, when you use quotes.



                  The second command:



                  cat /var/log/dpkg.log | grep install


                  This command also matches strings, that contain install. For example "installed".




                  Test Case:

                  content of testfile:



                  foo
                  bar
                  foobar
                  foo bar


                  Run:



                  cat file1.txt | grep foo
                  foo
                  foobar
                  foo bar

                  cat file1.txt | grep -w foo
                  foo
                  foo bar

                  cat file1.txt | grep "foo "
                  foo bar





                  share|improve this answer














                  The first command:



                  cat /var/log/dpkg.log | grep " install "


                  As @ByteCommander pointed out, there may be a typo and the command should be



                  cat /var/log/dpkg.log | grep " install "


                  This would match the string install with a trailing and a leading whitespace. This could also be achieved by using grep -w "install". Also, the is not needed, when you use quotes.



                  The second command:



                  cat /var/log/dpkg.log | grep install


                  This command also matches strings, that contain install. For example "installed".




                  Test Case:

                  content of testfile:



                  foo
                  bar
                  foobar
                  foo bar


                  Run:



                  cat file1.txt | grep foo
                  foo
                  foobar
                  foo bar

                  cat file1.txt | grep -w foo
                  foo
                  foo bar

                  cat file1.txt | grep "foo "
                  foo bar






                  share|improve this answer













                  share|improve this answer




                  share|improve this answer










                  answered Dec 21 '15 at 17:10









                  Wayne_YuxWayne_Yux

                  4,2613 gold badges17 silver badges30 bronze badges




                  4,2613 gold badges17 silver badges30 bronze badges































                      draft saved

                      draft discarded















































                      Thanks for contributing an answer to Ask Ubuntu!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f712025%2fdifference-in-two-types-of-command-that-uses-grep%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown









                      Popular posts from this blog

                      Tamil (spriik) Luke uk diar | Nawigatjuun

                      Align equal signs while including text over equalitiesAMS align: left aligned text/math plus multicolumn alignmentMultiple alignmentsAligning equations in multiple placesNumbering and aligning an equation with multiple columnsHow to align one equation with another multline equationUsing \ in environments inside the begintabularxNumber equations and preserving alignment of equal signsHow can I align equations to the left and to the right?Double equation alignment problem within align enviromentAligned within align: Why are they right-aligned?

                      Training a classifier when some of the features are unknownWhy does Gradient Boosting regression predict negative values when there are no negative y-values in my training set?How to improve an existing (trained) classifier?What is effect when I set up some self defined predisctor variables?Why Matlab neural network classification returns decimal values on prediction dataset?Fitting and transforming text data in training, testing, and validation setsHow to quantify the performance of the classifier (multi-class SVM) using the test data?How do I control for some patients providing multiple samples in my training data?Training and Test setTraining a convolutional neural network for image denoising in MatlabShouldn't an autoencoder with #(neurons in hidden layer) = #(neurons in input layer) be “perfect”?