Formatting the output of grep when matching on multiple filesNumbering the output of grepSearch for a Value...

Why does the autopilot disengage even when it does not receive pilot input?

Storming Area 51

Robbers: The Hidden OEIS Substring

Why didn't Thanos kill all the Dwarves on Nidavellir?

How were Martello towers supposed to work?

How to achieve this rough borders and stippled illustration look?

Can fluent English speakers distinguish “steel”, “still” and “steal”?

<schwitz>, <zwinker> etc. Does German always use 2nd Person Singular Imperative verbs for emoticons? If so, why?

If your plane is out-of-control, why does military training instruct releasing the joystick to neutralize controls?

Why are Hobbits so fond of mushrooms?

Why would guns not work in the dungeon?

Book where the stars go black due to aliens stopping human observation collapsing quantum possibilities

How to know whether a Tamron lens is compatible with Canon EOS 60D?

What's an appropriate title for a person who deals with conflicts of an Empire?

Does the Dispel Magic spell work on the Mirror Image spell?

Professor falsely accusing me of cheating in a class he does not teach, two months after end of the class. What precautions should I take?

Did any of the founding fathers anticipate Lysander Spooner's criticism of the constitution?

Why do players in the past play much longer tournaments than today's top players?

How do Windows version numbers work?

Does Google Maps take into account hills/inclines for route times?

Why do Americans say "less than five people"?

Setting MAC field to all-zero to indicate unencrypted data

What explains 9 speed cassettes price differences?

Why do people keep referring to Leia as Princess Leia, even after the destruction of Alderaan?



Formatting the output of grep when matching on multiple files


Numbering the output of grepSearch for a Value only in one column w.o using awk, sed, or perlExtend grep to find a match after the first matchgrep pattern exacly matching from file and search only in first columnGrep that shows the pattern line and the matching linegrep script - output lines at the same time into echoGrep --line-buffered, can I search the same buffer with the results of the first grep?Grep multiple files and output to multiple files in a single commandgrep dynamically multiple files with customized outputHow to split an output to two files with grep?






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







4















When searching on multiple files, the output of grep looks something like this:



{FILE}:{MATCH}


This is a problem since if I double-click on the {FILE} portion, I will at least also select (and copy) the : and possibly some of the match. How can I get grep to instead format its output something like this:



{FILE} : {MATCH}


Basically, I want to insert a space before the column. (and optionally one after)










share|improve this question































    4















    When searching on multiple files, the output of grep looks something like this:



    {FILE}:{MATCH}


    This is a problem since if I double-click on the {FILE} portion, I will at least also select (and copy) the : and possibly some of the match. How can I get grep to instead format its output something like this:



    {FILE} : {MATCH}


    Basically, I want to insert a space before the column. (and optionally one after)










    share|improve this question



























      4












      4








      4


      1






      When searching on multiple files, the output of grep looks something like this:



      {FILE}:{MATCH}


      This is a problem since if I double-click on the {FILE} portion, I will at least also select (and copy) the : and possibly some of the match. How can I get grep to instead format its output something like this:



      {FILE} : {MATCH}


      Basically, I want to insert a space before the column. (and optionally one after)










      share|improve this question
















      When searching on multiple files, the output of grep looks something like this:



      {FILE}:{MATCH}


      This is a problem since if I double-click on the {FILE} portion, I will at least also select (and copy) the : and possibly some of the match. How can I get grep to instead format its output something like this:



      {FILE} : {MATCH}


      Basically, I want to insert a space before the column. (and optionally one after)







      grep






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 18 '14 at 20:03









      muru

      41.5k5 gold badges101 silver badges175 bronze badges




      41.5k5 gold badges101 silver badges175 bronze badges










      asked Nov 18 '14 at 19:35









      azaniazani

      1381 gold badge1 silver badge4 bronze badges




      1381 gold badge1 silver badge4 bronze badges






















          8 Answers
          8






          active

          oldest

          votes


















          6














          grep -T will work 7/8ths of the time.



          % for f in a ab abc abcd abcde abcdef abcdefg abcdefgh; do echo pattern > $f; done
          % grep -T pattern *
          a :pattern
          ab :pattern
          abc :pattern
          abcd :pattern
          abcde :pattern
          abcdef :pattern
          abcdefg:pattern
          abcdefgh :pattern


          From the GNU grep manual:




          -T
          --initial-tab



          Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H, -n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum-size field width.







          share|improve this answer

































            6














            This cannot be done by grep itself as far as I can tell. Assuming your filenames don't have a : in them:



            grep ... | sed 's/:/ : /'


            Only the first : will be padded.



            Of course, you can tell grep to only print filenames:



            grep -l ...





            share|improve this answer































              6














              What constitutes a word as far as selection with double-clicking is concerned is terminal (and/or X toolkit) dependant and for some terminals, customizable.



              For xterm, characters are organised in classes (letters, spaces...) and double clicking selects adjacent characters of the same class.



              The default is described there. In that default, : is not in the same class as / itself not in the same class as letters or digits.



              Some systems change that default by providing a resource file for xterm like /etc/X11/app-defaults/XTerm.



              On a Linux Mint system, in there, I find:



              ! Here is a pattern that is useful for double-clicking on a URL:
              *charClass: 33:48,35:48,37-38:48,43-47:48,58:48,61:48,63-64:48,95:48,126:48


              That puts characters 58 (:) and 47 in the same class as letters and digits (48).



              What you could do is change that to leave : in its own class via your own resource file.



              For instance, if you add:



              XTerm*charClass: 33:48,35:48,37-38:48,43-47:48,61:48,63-64:48,95:48,126:48


              to your ~/".Xdefaults-$(uname -n)", then double clicking on the file name will stop at the :.



              You can experiment with it with:



              xterm -cc 33:48,35:48,37-38:48,43-47:48,61:48,63-64:48,95:48,126:48


              You can also define a different selection method on triple or quadruple click as a regular expression. For instance



              XTerm*on3Clicks: regex [^:]+


              Would select sequences of non-colon characters upon triple-click.






              share|improve this answer


























              • If there was a way to have a "runner-up" this would be it. The accepted answer solves my problem well-enough, but you gave me a good solution that attacks my problem. Thanks.

                – azani
                Nov 19 '14 at 1:05



















              1














              Awk works for me:



              grep string files | awk -F":" {'print $1" : "substr($0,index($0,$2))'}


              Just a bit of explanation, if it would be helpful: The format {FILE}:{MATCH} from a multi-file grep is piped to Awk. Awk is told to use a colon (-F":") as a delimiter for identifying fields and then the following reformatting occurs: Print the first field (FILE), then print " : ", then print everything until the end of the line beginning where the second field (MATCH) starts. This should account for multiple ":" in the match (thanks muru).






              share|improve this answer


























              • This will have problems if there's a : in the matched text.

                – muru
                Nov 18 '14 at 19:57











              • This will have problems if there's a : in the filename -- but that's hard to avoid.

                – Scott
                Nov 19 '14 at 0:40











              • @AGHz you update will print the whole file name but it still will not correctly separate the name from the match when the file names contain :.

                – terdon
                Nov 19 '14 at 3:43



















              0














              As muru said, sed accepts input streams aka. files. Therefore, adding -l to grep will output files instead of text. Pipe it and use xargs.



              grep -l ... | xargs sed 's/}:{/ : /'


              You might need -i parameter. More here.



              Note: You don't have to escape in this case because you are neither using regular expressions nor the -e parameter for sed, so it will just search for the anything you put there. It is safer to include the curly brackets as your text might have semicolons as well.






              share|improve this answer































                0














                I would pass the output of grep command to Perl like below.



                grep ... | perl -pe 's/(?<=:)|(?=:)/ /g'


                Example:



                $ echo '{FILE}:{MATCH}' | perl -pe 's/(?<=:)|(?=:)/ /g'
                {FILE} : {MATCH}


                Explanation:





                • (?<=:) Match the boundary which exists after :


                • | OR


                • (?=:) Match the boundary which exists before :

                • Replace all the matched boundaries with a space.






                share|improve this answer































                  0














                  This is grossly inefficient,
                  as it results in spawning a new grep process for each input file, but:



                  Given a list of files (e.g., *), do



                  for f in file_list
                  do
                  grep --label="$f " --with-filename pattern < "$f"
                  done


                  --label=string says,
                  in effect, “When reading standard input,
                  pretend that the input filename is string.” 
                  --with-filename (-H for short) says, “Print the file name for each match.” 
                  This is the default when there is more than one file to search. 
                  IMNSHO, it should also be on by default when you specify --label,
                  but it doesn’t seem to work that way. 
                  Since my code (above) adds a space to the filename in the argument to --label,
                  you get output that looks like



                  filename :Line matching pattern


                  If your filenames are coming from find, do



                  find (path…) (expression) -exec sh -c 'grep --label="$1 " -H pattern < "$1"' sh {} ";"





                  share|improve this answer

































                    0














                    If you don't care about speed, then find the files in a loop. Make sure grep does not show the file name (hidden by default if given only one file), and the prepend the file name with sed. Add -s to silence 'Is a directory' grep warnings. I used this solution because grep --label did not work for me.



                    find your_directory | while read f; do
                    grep "my_query" "$f" -s | sed "s:^:[$f] :"
                    done


                    Output:
                    [your_directory/file name] my file contents






                    share|improve this answer


























                      Your Answer








                      StackExchange.ready(function() {
                      var channelOptions = {
                      tags: "".split(" "),
                      id: "106"
                      };
                      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: false,
                      noModals: true,
                      showLowRepImageUploadWarning: true,
                      reputationToPostImages: null,
                      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/3.0/"u003ecc by-sa 3.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%2funix.stackexchange.com%2fquestions%2f168710%2fformatting-the-output-of-grep-when-matching-on-multiple-files%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown

























                      8 Answers
                      8






                      active

                      oldest

                      votes








                      8 Answers
                      8






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      6














                      grep -T will work 7/8ths of the time.



                      % for f in a ab abc abcd abcde abcdef abcdefg abcdefgh; do echo pattern > $f; done
                      % grep -T pattern *
                      a :pattern
                      ab :pattern
                      abc :pattern
                      abcd :pattern
                      abcde :pattern
                      abcdef :pattern
                      abcdefg:pattern
                      abcdefgh :pattern


                      From the GNU grep manual:




                      -T
                      --initial-tab



                      Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H, -n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum-size field width.







                      share|improve this answer






























                        6














                        grep -T will work 7/8ths of the time.



                        % for f in a ab abc abcd abcde abcdef abcdefg abcdefgh; do echo pattern > $f; done
                        % grep -T pattern *
                        a :pattern
                        ab :pattern
                        abc :pattern
                        abcd :pattern
                        abcde :pattern
                        abcdef :pattern
                        abcdefg:pattern
                        abcdefgh :pattern


                        From the GNU grep manual:




                        -T
                        --initial-tab



                        Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H, -n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum-size field width.







                        share|improve this answer




























                          6












                          6








                          6







                          grep -T will work 7/8ths of the time.



                          % for f in a ab abc abcd abcde abcdef abcdefg abcdefgh; do echo pattern > $f; done
                          % grep -T pattern *
                          a :pattern
                          ab :pattern
                          abc :pattern
                          abcd :pattern
                          abcde :pattern
                          abcdef :pattern
                          abcdefg:pattern
                          abcdefgh :pattern


                          From the GNU grep manual:




                          -T
                          --initial-tab



                          Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H, -n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum-size field width.







                          share|improve this answer















                          grep -T will work 7/8ths of the time.



                          % for f in a ab abc abcd abcde abcdef abcdefg abcdefgh; do echo pattern > $f; done
                          % grep -T pattern *
                          a :pattern
                          ab :pattern
                          abc :pattern
                          abcd :pattern
                          abcde :pattern
                          abcdef :pattern
                          abcdefg:pattern
                          abcdefgh :pattern


                          From the GNU grep manual:




                          -T
                          --initial-tab



                          Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H, -n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum-size field width.








                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 19 '14 at 2:12









                          Cristian Ciupitu

                          2,1081 gold badge17 silver badges23 bronze badges




                          2,1081 gold badge17 silver badges23 bronze badges










                          answered Nov 18 '14 at 20:21









                          o11co11c

                          1,0785 silver badges11 bronze badges




                          1,0785 silver badges11 bronze badges

























                              6














                              This cannot be done by grep itself as far as I can tell. Assuming your filenames don't have a : in them:



                              grep ... | sed 's/:/ : /'


                              Only the first : will be padded.



                              Of course, you can tell grep to only print filenames:



                              grep -l ...





                              share|improve this answer




























                                6














                                This cannot be done by grep itself as far as I can tell. Assuming your filenames don't have a : in them:



                                grep ... | sed 's/:/ : /'


                                Only the first : will be padded.



                                Of course, you can tell grep to only print filenames:



                                grep -l ...





                                share|improve this answer


























                                  6












                                  6








                                  6







                                  This cannot be done by grep itself as far as I can tell. Assuming your filenames don't have a : in them:



                                  grep ... | sed 's/:/ : /'


                                  Only the first : will be padded.



                                  Of course, you can tell grep to only print filenames:



                                  grep -l ...





                                  share|improve this answer













                                  This cannot be done by grep itself as far as I can tell. Assuming your filenames don't have a : in them:



                                  grep ... | sed 's/:/ : /'


                                  Only the first : will be padded.



                                  Of course, you can tell grep to only print filenames:



                                  grep -l ...






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Nov 18 '14 at 19:58









                                  murumuru

                                  41.5k5 gold badges101 silver badges175 bronze badges




                                  41.5k5 gold badges101 silver badges175 bronze badges























                                      6














                                      What constitutes a word as far as selection with double-clicking is concerned is terminal (and/or X toolkit) dependant and for some terminals, customizable.



                                      For xterm, characters are organised in classes (letters, spaces...) and double clicking selects adjacent characters of the same class.



                                      The default is described there. In that default, : is not in the same class as / itself not in the same class as letters or digits.



                                      Some systems change that default by providing a resource file for xterm like /etc/X11/app-defaults/XTerm.



                                      On a Linux Mint system, in there, I find:



                                      ! Here is a pattern that is useful for double-clicking on a URL:
                                      *charClass: 33:48,35:48,37-38:48,43-47:48,58:48,61:48,63-64:48,95:48,126:48


                                      That puts characters 58 (:) and 47 in the same class as letters and digits (48).



                                      What you could do is change that to leave : in its own class via your own resource file.



                                      For instance, if you add:



                                      XTerm*charClass: 33:48,35:48,37-38:48,43-47:48,61:48,63-64:48,95:48,126:48


                                      to your ~/".Xdefaults-$(uname -n)", then double clicking on the file name will stop at the :.



                                      You can experiment with it with:



                                      xterm -cc 33:48,35:48,37-38:48,43-47:48,61:48,63-64:48,95:48,126:48


                                      You can also define a different selection method on triple or quadruple click as a regular expression. For instance



                                      XTerm*on3Clicks: regex [^:]+


                                      Would select sequences of non-colon characters upon triple-click.






                                      share|improve this answer


























                                      • If there was a way to have a "runner-up" this would be it. The accepted answer solves my problem well-enough, but you gave me a good solution that attacks my problem. Thanks.

                                        – azani
                                        Nov 19 '14 at 1:05
















                                      6














                                      What constitutes a word as far as selection with double-clicking is concerned is terminal (and/or X toolkit) dependant and for some terminals, customizable.



                                      For xterm, characters are organised in classes (letters, spaces...) and double clicking selects adjacent characters of the same class.



                                      The default is described there. In that default, : is not in the same class as / itself not in the same class as letters or digits.



                                      Some systems change that default by providing a resource file for xterm like /etc/X11/app-defaults/XTerm.



                                      On a Linux Mint system, in there, I find:



                                      ! Here is a pattern that is useful for double-clicking on a URL:
                                      *charClass: 33:48,35:48,37-38:48,43-47:48,58:48,61:48,63-64:48,95:48,126:48


                                      That puts characters 58 (:) and 47 in the same class as letters and digits (48).



                                      What you could do is change that to leave : in its own class via your own resource file.



                                      For instance, if you add:



                                      XTerm*charClass: 33:48,35:48,37-38:48,43-47:48,61:48,63-64:48,95:48,126:48


                                      to your ~/".Xdefaults-$(uname -n)", then double clicking on the file name will stop at the :.



                                      You can experiment with it with:



                                      xterm -cc 33:48,35:48,37-38:48,43-47:48,61:48,63-64:48,95:48,126:48


                                      You can also define a different selection method on triple or quadruple click as a regular expression. For instance



                                      XTerm*on3Clicks: regex [^:]+


                                      Would select sequences of non-colon characters upon triple-click.






                                      share|improve this answer


























                                      • If there was a way to have a "runner-up" this would be it. The accepted answer solves my problem well-enough, but you gave me a good solution that attacks my problem. Thanks.

                                        – azani
                                        Nov 19 '14 at 1:05














                                      6












                                      6








                                      6







                                      What constitutes a word as far as selection with double-clicking is concerned is terminal (and/or X toolkit) dependant and for some terminals, customizable.



                                      For xterm, characters are organised in classes (letters, spaces...) and double clicking selects adjacent characters of the same class.



                                      The default is described there. In that default, : is not in the same class as / itself not in the same class as letters or digits.



                                      Some systems change that default by providing a resource file for xterm like /etc/X11/app-defaults/XTerm.



                                      On a Linux Mint system, in there, I find:



                                      ! Here is a pattern that is useful for double-clicking on a URL:
                                      *charClass: 33:48,35:48,37-38:48,43-47:48,58:48,61:48,63-64:48,95:48,126:48


                                      That puts characters 58 (:) and 47 in the same class as letters and digits (48).



                                      What you could do is change that to leave : in its own class via your own resource file.



                                      For instance, if you add:



                                      XTerm*charClass: 33:48,35:48,37-38:48,43-47:48,61:48,63-64:48,95:48,126:48


                                      to your ~/".Xdefaults-$(uname -n)", then double clicking on the file name will stop at the :.



                                      You can experiment with it with:



                                      xterm -cc 33:48,35:48,37-38:48,43-47:48,61:48,63-64:48,95:48,126:48


                                      You can also define a different selection method on triple or quadruple click as a regular expression. For instance



                                      XTerm*on3Clicks: regex [^:]+


                                      Would select sequences of non-colon characters upon triple-click.






                                      share|improve this answer















                                      What constitutes a word as far as selection with double-clicking is concerned is terminal (and/or X toolkit) dependant and for some terminals, customizable.



                                      For xterm, characters are organised in classes (letters, spaces...) and double clicking selects adjacent characters of the same class.



                                      The default is described there. In that default, : is not in the same class as / itself not in the same class as letters or digits.



                                      Some systems change that default by providing a resource file for xterm like /etc/X11/app-defaults/XTerm.



                                      On a Linux Mint system, in there, I find:



                                      ! Here is a pattern that is useful for double-clicking on a URL:
                                      *charClass: 33:48,35:48,37-38:48,43-47:48,58:48,61:48,63-64:48,95:48,126:48


                                      That puts characters 58 (:) and 47 in the same class as letters and digits (48).



                                      What you could do is change that to leave : in its own class via your own resource file.



                                      For instance, if you add:



                                      XTerm*charClass: 33:48,35:48,37-38:48,43-47:48,61:48,63-64:48,95:48,126:48


                                      to your ~/".Xdefaults-$(uname -n)", then double clicking on the file name will stop at the :.



                                      You can experiment with it with:



                                      xterm -cc 33:48,35:48,37-38:48,43-47:48,61:48,63-64:48,95:48,126:48


                                      You can also define a different selection method on triple or quadruple click as a regular expression. For instance



                                      XTerm*on3Clicks: regex [^:]+


                                      Would select sequences of non-colon characters upon triple-click.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Nov 18 '14 at 21:00

























                                      answered Nov 18 '14 at 20:43









                                      Stéphane ChazelasStéphane Chazelas

                                      325k57 gold badges628 silver badges997 bronze badges




                                      325k57 gold badges628 silver badges997 bronze badges













                                      • If there was a way to have a "runner-up" this would be it. The accepted answer solves my problem well-enough, but you gave me a good solution that attacks my problem. Thanks.

                                        – azani
                                        Nov 19 '14 at 1:05



















                                      • If there was a way to have a "runner-up" this would be it. The accepted answer solves my problem well-enough, but you gave me a good solution that attacks my problem. Thanks.

                                        – azani
                                        Nov 19 '14 at 1:05

















                                      If there was a way to have a "runner-up" this would be it. The accepted answer solves my problem well-enough, but you gave me a good solution that attacks my problem. Thanks.

                                      – azani
                                      Nov 19 '14 at 1:05





                                      If there was a way to have a "runner-up" this would be it. The accepted answer solves my problem well-enough, but you gave me a good solution that attacks my problem. Thanks.

                                      – azani
                                      Nov 19 '14 at 1:05











                                      1














                                      Awk works for me:



                                      grep string files | awk -F":" {'print $1" : "substr($0,index($0,$2))'}


                                      Just a bit of explanation, if it would be helpful: The format {FILE}:{MATCH} from a multi-file grep is piped to Awk. Awk is told to use a colon (-F":") as a delimiter for identifying fields and then the following reformatting occurs: Print the first field (FILE), then print " : ", then print everything until the end of the line beginning where the second field (MATCH) starts. This should account for multiple ":" in the match (thanks muru).






                                      share|improve this answer


























                                      • This will have problems if there's a : in the matched text.

                                        – muru
                                        Nov 18 '14 at 19:57











                                      • This will have problems if there's a : in the filename -- but that's hard to avoid.

                                        – Scott
                                        Nov 19 '14 at 0:40











                                      • @AGHz you update will print the whole file name but it still will not correctly separate the name from the match when the file names contain :.

                                        – terdon
                                        Nov 19 '14 at 3:43
















                                      1














                                      Awk works for me:



                                      grep string files | awk -F":" {'print $1" : "substr($0,index($0,$2))'}


                                      Just a bit of explanation, if it would be helpful: The format {FILE}:{MATCH} from a multi-file grep is piped to Awk. Awk is told to use a colon (-F":") as a delimiter for identifying fields and then the following reformatting occurs: Print the first field (FILE), then print " : ", then print everything until the end of the line beginning where the second field (MATCH) starts. This should account for multiple ":" in the match (thanks muru).






                                      share|improve this answer


























                                      • This will have problems if there's a : in the matched text.

                                        – muru
                                        Nov 18 '14 at 19:57











                                      • This will have problems if there's a : in the filename -- but that's hard to avoid.

                                        – Scott
                                        Nov 19 '14 at 0:40











                                      • @AGHz you update will print the whole file name but it still will not correctly separate the name from the match when the file names contain :.

                                        – terdon
                                        Nov 19 '14 at 3:43














                                      1












                                      1








                                      1







                                      Awk works for me:



                                      grep string files | awk -F":" {'print $1" : "substr($0,index($0,$2))'}


                                      Just a bit of explanation, if it would be helpful: The format {FILE}:{MATCH} from a multi-file grep is piped to Awk. Awk is told to use a colon (-F":") as a delimiter for identifying fields and then the following reformatting occurs: Print the first field (FILE), then print " : ", then print everything until the end of the line beginning where the second field (MATCH) starts. This should account for multiple ":" in the match (thanks muru).






                                      share|improve this answer















                                      Awk works for me:



                                      grep string files | awk -F":" {'print $1" : "substr($0,index($0,$2))'}


                                      Just a bit of explanation, if it would be helpful: The format {FILE}:{MATCH} from a multi-file grep is piped to Awk. Awk is told to use a colon (-F":") as a delimiter for identifying fields and then the following reformatting occurs: Print the first field (FILE), then print " : ", then print everything until the end of the line beginning where the second field (MATCH) starts. This should account for multiple ":" in the match (thanks muru).







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Nov 18 '14 at 20:12

























                                      answered Nov 18 '14 at 19:41









                                      AGHzAGHz

                                      863 bronze badges




                                      863 bronze badges













                                      • This will have problems if there's a : in the matched text.

                                        – muru
                                        Nov 18 '14 at 19:57











                                      • This will have problems if there's a : in the filename -- but that's hard to avoid.

                                        – Scott
                                        Nov 19 '14 at 0:40











                                      • @AGHz you update will print the whole file name but it still will not correctly separate the name from the match when the file names contain :.

                                        – terdon
                                        Nov 19 '14 at 3:43



















                                      • This will have problems if there's a : in the matched text.

                                        – muru
                                        Nov 18 '14 at 19:57











                                      • This will have problems if there's a : in the filename -- but that's hard to avoid.

                                        – Scott
                                        Nov 19 '14 at 0:40











                                      • @AGHz you update will print the whole file name but it still will not correctly separate the name from the match when the file names contain :.

                                        – terdon
                                        Nov 19 '14 at 3:43

















                                      This will have problems if there's a : in the matched text.

                                      – muru
                                      Nov 18 '14 at 19:57





                                      This will have problems if there's a : in the matched text.

                                      – muru
                                      Nov 18 '14 at 19:57













                                      This will have problems if there's a : in the filename -- but that's hard to avoid.

                                      – Scott
                                      Nov 19 '14 at 0:40





                                      This will have problems if there's a : in the filename -- but that's hard to avoid.

                                      – Scott
                                      Nov 19 '14 at 0:40













                                      @AGHz you update will print the whole file name but it still will not correctly separate the name from the match when the file names contain :.

                                      – terdon
                                      Nov 19 '14 at 3:43





                                      @AGHz you update will print the whole file name but it still will not correctly separate the name from the match when the file names contain :.

                                      – terdon
                                      Nov 19 '14 at 3:43











                                      0














                                      As muru said, sed accepts input streams aka. files. Therefore, adding -l to grep will output files instead of text. Pipe it and use xargs.



                                      grep -l ... | xargs sed 's/}:{/ : /'


                                      You might need -i parameter. More here.



                                      Note: You don't have to escape in this case because you are neither using regular expressions nor the -e parameter for sed, so it will just search for the anything you put there. It is safer to include the curly brackets as your text might have semicolons as well.






                                      share|improve this answer




























                                        0














                                        As muru said, sed accepts input streams aka. files. Therefore, adding -l to grep will output files instead of text. Pipe it and use xargs.



                                        grep -l ... | xargs sed 's/}:{/ : /'


                                        You might need -i parameter. More here.



                                        Note: You don't have to escape in this case because you are neither using regular expressions nor the -e parameter for sed, so it will just search for the anything you put there. It is safer to include the curly brackets as your text might have semicolons as well.






                                        share|improve this answer


























                                          0












                                          0








                                          0







                                          As muru said, sed accepts input streams aka. files. Therefore, adding -l to grep will output files instead of text. Pipe it and use xargs.



                                          grep -l ... | xargs sed 's/}:{/ : /'


                                          You might need -i parameter. More here.



                                          Note: You don't have to escape in this case because you are neither using regular expressions nor the -e parameter for sed, so it will just search for the anything you put there. It is safer to include the curly brackets as your text might have semicolons as well.






                                          share|improve this answer













                                          As muru said, sed accepts input streams aka. files. Therefore, adding -l to grep will output files instead of text. Pipe it and use xargs.



                                          grep -l ... | xargs sed 's/}:{/ : /'


                                          You might need -i parameter. More here.



                                          Note: You don't have to escape in this case because you are neither using regular expressions nor the -e parameter for sed, so it will just search for the anything you put there. It is safer to include the curly brackets as your text might have semicolons as well.







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Nov 18 '14 at 20:27









                                          AtiehAtieh

                                          1481 gold badge2 silver badges8 bronze badges




                                          1481 gold badge2 silver badges8 bronze badges























                                              0














                                              I would pass the output of grep command to Perl like below.



                                              grep ... | perl -pe 's/(?<=:)|(?=:)/ /g'


                                              Example:



                                              $ echo '{FILE}:{MATCH}' | perl -pe 's/(?<=:)|(?=:)/ /g'
                                              {FILE} : {MATCH}


                                              Explanation:





                                              • (?<=:) Match the boundary which exists after :


                                              • | OR


                                              • (?=:) Match the boundary which exists before :

                                              • Replace all the matched boundaries with a space.






                                              share|improve this answer




























                                                0














                                                I would pass the output of grep command to Perl like below.



                                                grep ... | perl -pe 's/(?<=:)|(?=:)/ /g'


                                                Example:



                                                $ echo '{FILE}:{MATCH}' | perl -pe 's/(?<=:)|(?=:)/ /g'
                                                {FILE} : {MATCH}


                                                Explanation:





                                                • (?<=:) Match the boundary which exists after :


                                                • | OR


                                                • (?=:) Match the boundary which exists before :

                                                • Replace all the matched boundaries with a space.






                                                share|improve this answer


























                                                  0












                                                  0








                                                  0







                                                  I would pass the output of grep command to Perl like below.



                                                  grep ... | perl -pe 's/(?<=:)|(?=:)/ /g'


                                                  Example:



                                                  $ echo '{FILE}:{MATCH}' | perl -pe 's/(?<=:)|(?=:)/ /g'
                                                  {FILE} : {MATCH}


                                                  Explanation:





                                                  • (?<=:) Match the boundary which exists after :


                                                  • | OR


                                                  • (?=:) Match the boundary which exists before :

                                                  • Replace all the matched boundaries with a space.






                                                  share|improve this answer













                                                  I would pass the output of grep command to Perl like below.



                                                  grep ... | perl -pe 's/(?<=:)|(?=:)/ /g'


                                                  Example:



                                                  $ echo '{FILE}:{MATCH}' | perl -pe 's/(?<=:)|(?=:)/ /g'
                                                  {FILE} : {MATCH}


                                                  Explanation:





                                                  • (?<=:) Match the boundary which exists after :


                                                  • | OR


                                                  • (?=:) Match the boundary which exists before :

                                                  • Replace all the matched boundaries with a space.







                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Nov 19 '14 at 3:31









                                                  Avinash RajAvinash Raj

                                                  2,6523 gold badges12 silver badges28 bronze badges




                                                  2,6523 gold badges12 silver badges28 bronze badges























                                                      0














                                                      This is grossly inefficient,
                                                      as it results in spawning a new grep process for each input file, but:



                                                      Given a list of files (e.g., *), do



                                                      for f in file_list
                                                      do
                                                      grep --label="$f " --with-filename pattern < "$f"
                                                      done


                                                      --label=string says,
                                                      in effect, “When reading standard input,
                                                      pretend that the input filename is string.” 
                                                      --with-filename (-H for short) says, “Print the file name for each match.” 
                                                      This is the default when there is more than one file to search. 
                                                      IMNSHO, it should also be on by default when you specify --label,
                                                      but it doesn’t seem to work that way. 
                                                      Since my code (above) adds a space to the filename in the argument to --label,
                                                      you get output that looks like



                                                      filename :Line matching pattern


                                                      If your filenames are coming from find, do



                                                      find (path…) (expression) -exec sh -c 'grep --label="$1 " -H pattern < "$1"' sh {} ";"





                                                      share|improve this answer






























                                                        0














                                                        This is grossly inefficient,
                                                        as it results in spawning a new grep process for each input file, but:



                                                        Given a list of files (e.g., *), do



                                                        for f in file_list
                                                        do
                                                        grep --label="$f " --with-filename pattern < "$f"
                                                        done


                                                        --label=string says,
                                                        in effect, “When reading standard input,
                                                        pretend that the input filename is string.” 
                                                        --with-filename (-H for short) says, “Print the file name for each match.” 
                                                        This is the default when there is more than one file to search. 
                                                        IMNSHO, it should also be on by default when you specify --label,
                                                        but it doesn’t seem to work that way. 
                                                        Since my code (above) adds a space to the filename in the argument to --label,
                                                        you get output that looks like



                                                        filename :Line matching pattern


                                                        If your filenames are coming from find, do



                                                        find (path…) (expression) -exec sh -c 'grep --label="$1 " -H pattern < "$1"' sh {} ";"





                                                        share|improve this answer




























                                                          0












                                                          0








                                                          0







                                                          This is grossly inefficient,
                                                          as it results in spawning a new grep process for each input file, but:



                                                          Given a list of files (e.g., *), do



                                                          for f in file_list
                                                          do
                                                          grep --label="$f " --with-filename pattern < "$f"
                                                          done


                                                          --label=string says,
                                                          in effect, “When reading standard input,
                                                          pretend that the input filename is string.” 
                                                          --with-filename (-H for short) says, “Print the file name for each match.” 
                                                          This is the default when there is more than one file to search. 
                                                          IMNSHO, it should also be on by default when you specify --label,
                                                          but it doesn’t seem to work that way. 
                                                          Since my code (above) adds a space to the filename in the argument to --label,
                                                          you get output that looks like



                                                          filename :Line matching pattern


                                                          If your filenames are coming from find, do



                                                          find (path…) (expression) -exec sh -c 'grep --label="$1 " -H pattern < "$1"' sh {} ";"





                                                          share|improve this answer















                                                          This is grossly inefficient,
                                                          as it results in spawning a new grep process for each input file, but:



                                                          Given a list of files (e.g., *), do



                                                          for f in file_list
                                                          do
                                                          grep --label="$f " --with-filename pattern < "$f"
                                                          done


                                                          --label=string says,
                                                          in effect, “When reading standard input,
                                                          pretend that the input filename is string.” 
                                                          --with-filename (-H for short) says, “Print the file name for each match.” 
                                                          This is the default when there is more than one file to search. 
                                                          IMNSHO, it should also be on by default when you specify --label,
                                                          but it doesn’t seem to work that way. 
                                                          Since my code (above) adds a space to the filename in the argument to --label,
                                                          you get output that looks like



                                                          filename :Line matching pattern


                                                          If your filenames are coming from find, do



                                                          find (path…) (expression) -exec sh -c 'grep --label="$1 " -H pattern < "$1"' sh {} ";"






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Jul 5 '17 at 18:16

























                                                          answered Nov 19 '14 at 1:03









                                                          ScottScott

                                                          7,4255 gold badges29 silver badges53 bronze badges




                                                          7,4255 gold badges29 silver badges53 bronze badges























                                                              0














                                                              If you don't care about speed, then find the files in a loop. Make sure grep does not show the file name (hidden by default if given only one file), and the prepend the file name with sed. Add -s to silence 'Is a directory' grep warnings. I used this solution because grep --label did not work for me.



                                                              find your_directory | while read f; do
                                                              grep "my_query" "$f" -s | sed "s:^:[$f] :"
                                                              done


                                                              Output:
                                                              [your_directory/file name] my file contents






                                                              share|improve this answer




























                                                                0














                                                                If you don't care about speed, then find the files in a loop. Make sure grep does not show the file name (hidden by default if given only one file), and the prepend the file name with sed. Add -s to silence 'Is a directory' grep warnings. I used this solution because grep --label did not work for me.



                                                                find your_directory | while read f; do
                                                                grep "my_query" "$f" -s | sed "s:^:[$f] :"
                                                                done


                                                                Output:
                                                                [your_directory/file name] my file contents






                                                                share|improve this answer


























                                                                  0












                                                                  0








                                                                  0







                                                                  If you don't care about speed, then find the files in a loop. Make sure grep does not show the file name (hidden by default if given only one file), and the prepend the file name with sed. Add -s to silence 'Is a directory' grep warnings. I used this solution because grep --label did not work for me.



                                                                  find your_directory | while read f; do
                                                                  grep "my_query" "$f" -s | sed "s:^:[$f] :"
                                                                  done


                                                                  Output:
                                                                  [your_directory/file name] my file contents






                                                                  share|improve this answer













                                                                  If you don't care about speed, then find the files in a loop. Make sure grep does not show the file name (hidden by default if given only one file), and the prepend the file name with sed. Add -s to silence 'Is a directory' grep warnings. I used this solution because grep --label did not work for me.



                                                                  find your_directory | while read f; do
                                                                  grep "my_query" "$f" -s | sed "s:^:[$f] :"
                                                                  done


                                                                  Output:
                                                                  [your_directory/file name] my file contents







                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered 43 mins ago









                                                                  aggregate1166877aggregate1166877

                                                                  3402 gold badges3 silver badges15 bronze badges




                                                                  3402 gold badges3 silver badges15 bronze badges






























                                                                      draft saved

                                                                      draft discarded




















































                                                                      Thanks for contributing an answer to Unix & Linux Stack Exchange!


                                                                      • 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%2funix.stackexchange.com%2fquestions%2f168710%2fformatting-the-output-of-grep-when-matching-on-multiple-files%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

                                                                      Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                                                                      Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                                                                      Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...