How to search and replace a string with newlines on commandline in a file2019 Community Moderator ElectionCase-preserving search and replace in vim?search and replace stringextract certain string, search and replace or keep a longer string contain the extracted valueSearch and Replace questionSearch a line and replace linesearch string in files and replace it incrementallyVim Search and Replace - RegexHow to search and replace in the entire system?Return multiple regex match groups from an nmap returned resultsvim regex search and replace

Taxes on Dividends in a Roth IRA

What fields between the rationals and the reals allow a good notion of 2D distance?

Do we have to expect a queue for the shuttle from Watford Junction to Harry Potter Studio?

Does an advisor owe his/her student anything? Will an advisor keep a PhD student only out of pity?

How to make money from a browser who sees 5 seconds into the future of any web page?

Why do some congregations only make noise at certain occasions of Haman?

How does electrical safety system work on ISS?

Why Shazam when there is already Superman?

Strong empirical falsification of quantum mechanics based on vacuum energy density?

Why can't the Brexit deadlock in the UK parliament be solved with a plurality vote?

Is it allowed to activate the ability of multiple planeswalkers in a single turn?

How to draw a matrix with arrows in limited space

Is this toilet slogan correct usage of the English language?

What is going on with gets(stdin) on the site coderbyte?

Why is it that I can sometimes guess the next note?

Delete multiple columns using awk or sed

Does Doodling or Improvising on the Piano Have Any Benefits?

How can ping know if my host is down

Giving feedback to someone without sounding prejudiced

Mimic lecturing on blackboard, facing audience

Why is the Sun approximated as a black body at ~ 5800 K?

Microchip documentation does not label CAN buss pins on micro controller pinout diagram

Are Captain Marvel's powers affected by Thanos breaking the Tesseract and claiming the stone?

How to convince somebody that he is fit for something else, but not this job?



How to search and replace a string with newlines on commandline in a file



2019 Community Moderator ElectionCase-preserving search and replace in vim?search and replace stringextract certain string, search and replace or keep a longer string contain the extracted valueSearch and Replace questionSearch a line and replace linesearch string in files and replace it incrementallyVim Search and Replace - RegexHow to search and replace in the entire system?Return multiple regex match groups from an nmap returned resultsvim regex search and replace










1















I want to replace all occurrences of a text string in a textfile on command line on CentOS 7.2.



Search-string: ).nPORT
Replacement-string: ). n0 closed portsnPORT


I know, this can be achieved with different tools like sed, awk, tr, ... but I can't figure out an easy way to do this and be able to understand the command (important ;-)). For me the biggest problem are the newlines, without them, it is a very simple call to sed. But with newlines ...



Any suggestion with explanation is very welcome.



edited



Input



...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00090s latency).
PORT STATE SERVICE
21/tcp open ftp
...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00079s latency).
Not shown: 2 closed ports
PORT STATE SERVICE
22/tcp open ssh
|_banner: SSH-2.0-mpSSH_0.2.1
...


Output



...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00090s latency).
0 closed ports
PORT STATE SERVICE
21/tcp open ftp
...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00079s latency).
Not shown: 2 closed ports
PORT STATE SERVICE
22/tcp open ssh
|_banner: SSH-2.0-mpSSH_0.2.1
...









share|improve this question
























  • Please edit your question and add an example of your input file and the output you would expect from it.

    – terdon
    Jul 12 '16 at 11:43















1















I want to replace all occurrences of a text string in a textfile on command line on CentOS 7.2.



Search-string: ).nPORT
Replacement-string: ). n0 closed portsnPORT


I know, this can be achieved with different tools like sed, awk, tr, ... but I can't figure out an easy way to do this and be able to understand the command (important ;-)). For me the biggest problem are the newlines, without them, it is a very simple call to sed. But with newlines ...



Any suggestion with explanation is very welcome.



edited



Input



...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00090s latency).
PORT STATE SERVICE
21/tcp open ftp
...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00079s latency).
Not shown: 2 closed ports
PORT STATE SERVICE
22/tcp open ssh
|_banner: SSH-2.0-mpSSH_0.2.1
...


Output



...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00090s latency).
0 closed ports
PORT STATE SERVICE
21/tcp open ftp
...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00079s latency).
Not shown: 2 closed ports
PORT STATE SERVICE
22/tcp open ssh
|_banner: SSH-2.0-mpSSH_0.2.1
...









share|improve this question
























  • Please edit your question and add an example of your input file and the output you would expect from it.

    – terdon
    Jul 12 '16 at 11:43













1












1








1








I want to replace all occurrences of a text string in a textfile on command line on CentOS 7.2.



Search-string: ).nPORT
Replacement-string: ). n0 closed portsnPORT


I know, this can be achieved with different tools like sed, awk, tr, ... but I can't figure out an easy way to do this and be able to understand the command (important ;-)). For me the biggest problem are the newlines, without them, it is a very simple call to sed. But with newlines ...



Any suggestion with explanation is very welcome.



edited



Input



...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00090s latency).
PORT STATE SERVICE
21/tcp open ftp
...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00079s latency).
Not shown: 2 closed ports
PORT STATE SERVICE
22/tcp open ssh
|_banner: SSH-2.0-mpSSH_0.2.1
...


Output



...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00090s latency).
0 closed ports
PORT STATE SERVICE
21/tcp open ftp
...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00079s latency).
Not shown: 2 closed ports
PORT STATE SERVICE
22/tcp open ssh
|_banner: SSH-2.0-mpSSH_0.2.1
...









share|improve this question
















I want to replace all occurrences of a text string in a textfile on command line on CentOS 7.2.



Search-string: ).nPORT
Replacement-string: ). n0 closed portsnPORT


I know, this can be achieved with different tools like sed, awk, tr, ... but I can't figure out an easy way to do this and be able to understand the command (important ;-)). For me the biggest problem are the newlines, without them, it is a very simple call to sed. But with newlines ...



Any suggestion with explanation is very welcome.



edited



Input



...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00090s latency).
PORT STATE SERVICE
21/tcp open ftp
...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00079s latency).
Not shown: 2 closed ports
PORT STATE SERVICE
22/tcp open ssh
|_banner: SSH-2.0-mpSSH_0.2.1
...


Output



...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00090s latency).
0 closed ports
PORT STATE SERVICE
21/tcp open ftp
...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00079s latency).
Not shown: 2 closed ports
PORT STATE SERVICE
22/tcp open ssh
|_banner: SSH-2.0-mpSSH_0.2.1
...






sed search replace






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 12 '16 at 12:30







Christian Waidner

















asked Jul 12 '16 at 11:02









Christian WaidnerChristian Waidner

1064




1064












  • Please edit your question and add an example of your input file and the output you would expect from it.

    – terdon
    Jul 12 '16 at 11:43

















  • Please edit your question and add an example of your input file and the output you would expect from it.

    – terdon
    Jul 12 '16 at 11:43
















Please edit your question and add an example of your input file and the output you would expect from it.

– terdon
Jul 12 '16 at 11:43





Please edit your question and add an example of your input file and the output you would expect from it.

– terdon
Jul 12 '16 at 11:43










3 Answers
3






active

oldest

votes


















2














Here's one possible way



sed '/). $/ 
n
/^PORT/ i
0 closed ports
'


Testing



$ sed '/). $/ 
n
/^PORT/ i
0 closed ports
' < input
...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00090s latency).
0 closed ports
PORT STATE SERVICE
21/tcp open ftp
...
Nmap scan report for w.x.y.z (x.x.x.x)
Host is up (0.00079s latency).
Not shown: 2 closed ports
PORT STATE SERVICE
22/tcp open ssh
|_banner: SSH-2.0-mpSSH_0.2.1
...





share|improve this answer
































    0














    You can use N in sed to pull next line of input in the pattern space, and then work on two lines at once.



    As an example, conditionally pull the next line in when seeing a foo, and then do a replacement on both lines. (Note that consecutive lines with foo will break this.)



    echo -e "asfnfoonbar" | sed -e '/foo/N;s/onb/odnc/'


    Also, GNU sed has the -z option that separates "lines" on NUL characters instead of newlines. That will easily allow you to match on patterns crossing a newline, but will result in the string operations to run on the whole input at once, which might be a problem with large input.



    The surrounding structure should of course be taken in to account, it might influence the best way to do the edit.






    share|improve this answer
































      0














      A new version of GNU sed supports the -z option.




      Normally, sed reads a line by reading a string of characters up to the end-of-line character (new line or carriage return).

      The GNU version of sed added a feature in version 4.2.2 to use the "NULL" character instead. This can be useful if you have files that use the NULL as a record separator. Some GNU utilities can genertae output that uses a NULL instead a new line, such as "find . -print0" or "grep -lZ".




      You can use this option when you want sed to work over different lines.



      sed -z 's/)[.]nPORT/). n0 closed portsnPORT/g' inputfile


      Please note that your example input has a space after (0.00090s latency).






      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%2f295372%2fhow-to-search-and-replace-a-string-with-newlines-on-commandline-in-a-file%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









        2














        Here's one possible way



        sed '/). $/ 
        n
        /^PORT/ i
        0 closed ports
        '


        Testing



        $ sed '/). $/ 
        n
        /^PORT/ i
        0 closed ports
        ' < input
        ...
        Nmap scan report for w.x.y.z (x.x.x.x)
        Host is up (0.00090s latency).
        0 closed ports
        PORT STATE SERVICE
        21/tcp open ftp
        ...
        Nmap scan report for w.x.y.z (x.x.x.x)
        Host is up (0.00079s latency).
        Not shown: 2 closed ports
        PORT STATE SERVICE
        22/tcp open ssh
        |_banner: SSH-2.0-mpSSH_0.2.1
        ...





        share|improve this answer





























          2














          Here's one possible way



          sed '/). $/ 
          n
          /^PORT/ i
          0 closed ports
          '


          Testing



          $ sed '/). $/ 
          n
          /^PORT/ i
          0 closed ports
          ' < input
          ...
          Nmap scan report for w.x.y.z (x.x.x.x)
          Host is up (0.00090s latency).
          0 closed ports
          PORT STATE SERVICE
          21/tcp open ftp
          ...
          Nmap scan report for w.x.y.z (x.x.x.x)
          Host is up (0.00079s latency).
          Not shown: 2 closed ports
          PORT STATE SERVICE
          22/tcp open ssh
          |_banner: SSH-2.0-mpSSH_0.2.1
          ...





          share|improve this answer



























            2












            2








            2







            Here's one possible way



            sed '/). $/ 
            n
            /^PORT/ i
            0 closed ports
            '


            Testing



            $ sed '/). $/ 
            n
            /^PORT/ i
            0 closed ports
            ' < input
            ...
            Nmap scan report for w.x.y.z (x.x.x.x)
            Host is up (0.00090s latency).
            0 closed ports
            PORT STATE SERVICE
            21/tcp open ftp
            ...
            Nmap scan report for w.x.y.z (x.x.x.x)
            Host is up (0.00079s latency).
            Not shown: 2 closed ports
            PORT STATE SERVICE
            22/tcp open ssh
            |_banner: SSH-2.0-mpSSH_0.2.1
            ...





            share|improve this answer















            Here's one possible way



            sed '/). $/ 
            n
            /^PORT/ i
            0 closed ports
            '


            Testing



            $ sed '/). $/ 
            n
            /^PORT/ i
            0 closed ports
            ' < input
            ...
            Nmap scan report for w.x.y.z (x.x.x.x)
            Host is up (0.00090s latency).
            0 closed ports
            PORT STATE SERVICE
            21/tcp open ftp
            ...
            Nmap scan report for w.x.y.z (x.x.x.x)
            Host is up (0.00079s latency).
            Not shown: 2 closed ports
            PORT STATE SERVICE
            22/tcp open ssh
            |_banner: SSH-2.0-mpSSH_0.2.1
            ...






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jul 12 '16 at 13:22

























            answered Jul 12 '16 at 12:42









            steeldriversteeldriver

            37.2k45287




            37.2k45287























                0














                You can use N in sed to pull next line of input in the pattern space, and then work on two lines at once.



                As an example, conditionally pull the next line in when seeing a foo, and then do a replacement on both lines. (Note that consecutive lines with foo will break this.)



                echo -e "asfnfoonbar" | sed -e '/foo/N;s/onb/odnc/'


                Also, GNU sed has the -z option that separates "lines" on NUL characters instead of newlines. That will easily allow you to match on patterns crossing a newline, but will result in the string operations to run on the whole input at once, which might be a problem with large input.



                The surrounding structure should of course be taken in to account, it might influence the best way to do the edit.






                share|improve this answer





























                  0














                  You can use N in sed to pull next line of input in the pattern space, and then work on two lines at once.



                  As an example, conditionally pull the next line in when seeing a foo, and then do a replacement on both lines. (Note that consecutive lines with foo will break this.)



                  echo -e "asfnfoonbar" | sed -e '/foo/N;s/onb/odnc/'


                  Also, GNU sed has the -z option that separates "lines" on NUL characters instead of newlines. That will easily allow you to match on patterns crossing a newline, but will result in the string operations to run on the whole input at once, which might be a problem with large input.



                  The surrounding structure should of course be taken in to account, it might influence the best way to do the edit.






                  share|improve this answer



























                    0












                    0








                    0







                    You can use N in sed to pull next line of input in the pattern space, and then work on two lines at once.



                    As an example, conditionally pull the next line in when seeing a foo, and then do a replacement on both lines. (Note that consecutive lines with foo will break this.)



                    echo -e "asfnfoonbar" | sed -e '/foo/N;s/onb/odnc/'


                    Also, GNU sed has the -z option that separates "lines" on NUL characters instead of newlines. That will easily allow you to match on patterns crossing a newline, but will result in the string operations to run on the whole input at once, which might be a problem with large input.



                    The surrounding structure should of course be taken in to account, it might influence the best way to do the edit.






                    share|improve this answer















                    You can use N in sed to pull next line of input in the pattern space, and then work on two lines at once.



                    As an example, conditionally pull the next line in when seeing a foo, and then do a replacement on both lines. (Note that consecutive lines with foo will break this.)



                    echo -e "asfnfoonbar" | sed -e '/foo/N;s/onb/odnc/'


                    Also, GNU sed has the -z option that separates "lines" on NUL characters instead of newlines. That will easily allow you to match on patterns crossing a newline, but will result in the string operations to run on the whole input at once, which might be a problem with large input.



                    The surrounding structure should of course be taken in to account, it might influence the best way to do the edit.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jul 12 '16 at 11:48

























                    answered Jul 12 '16 at 11:34









                    ilkkachuilkkachu

                    62.2k10103179




                    62.2k10103179





















                        0














                        A new version of GNU sed supports the -z option.




                        Normally, sed reads a line by reading a string of characters up to the end-of-line character (new line or carriage return).

                        The GNU version of sed added a feature in version 4.2.2 to use the "NULL" character instead. This can be useful if you have files that use the NULL as a record separator. Some GNU utilities can genertae output that uses a NULL instead a new line, such as "find . -print0" or "grep -lZ".




                        You can use this option when you want sed to work over different lines.



                        sed -z 's/)[.]nPORT/). n0 closed portsnPORT/g' inputfile


                        Please note that your example input has a space after (0.00090s latency).






                        share|improve this answer



























                          0














                          A new version of GNU sed supports the -z option.




                          Normally, sed reads a line by reading a string of characters up to the end-of-line character (new line or carriage return).

                          The GNU version of sed added a feature in version 4.2.2 to use the "NULL" character instead. This can be useful if you have files that use the NULL as a record separator. Some GNU utilities can genertae output that uses a NULL instead a new line, such as "find . -print0" or "grep -lZ".




                          You can use this option when you want sed to work over different lines.



                          sed -z 's/)[.]nPORT/). n0 closed portsnPORT/g' inputfile


                          Please note that your example input has a space after (0.00090s latency).






                          share|improve this answer

























                            0












                            0








                            0







                            A new version of GNU sed supports the -z option.




                            Normally, sed reads a line by reading a string of characters up to the end-of-line character (new line or carriage return).

                            The GNU version of sed added a feature in version 4.2.2 to use the "NULL" character instead. This can be useful if you have files that use the NULL as a record separator. Some GNU utilities can genertae output that uses a NULL instead a new line, such as "find . -print0" or "grep -lZ".




                            You can use this option when you want sed to work over different lines.



                            sed -z 's/)[.]nPORT/). n0 closed portsnPORT/g' inputfile


                            Please note that your example input has a space after (0.00090s latency).






                            share|improve this answer













                            A new version of GNU sed supports the -z option.




                            Normally, sed reads a line by reading a string of characters up to the end-of-line character (new line or carriage return).

                            The GNU version of sed added a feature in version 4.2.2 to use the "NULL" character instead. This can be useful if you have files that use the NULL as a record separator. Some GNU utilities can genertae output that uses a NULL instead a new line, such as "find . -print0" or "grep -lZ".




                            You can use this option when you want sed to work over different lines.



                            sed -z 's/)[.]nPORT/). n0 closed portsnPORT/g' inputfile


                            Please note that your example input has a space after (0.00090s latency).







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered yesterday









                            Walter AWalter A

                            514210




                            514210



























                                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%2f295372%2fhow-to-search-and-replace-a-string-with-newlines-on-commandline-in-a-file%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

                                getting Checkpoint VPN SSL Network Extender working in the command lineHow to connect to CheckPoint VPN on Ubuntu 18.04LTS?Will the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayVPN SSL Network Extender in FirefoxLinux Checkpoint SNX tool configuration issuesCheck Point - Connect under Linux - snx + OTPSNX VPN Ububuntu 18.XXUsing Checkpoint VPN SSL Network Extender CLI with certificateVPN with network manager (nm-applet) is not workingWill the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayImport VPN config files to NetworkManager from command lineTrouble connecting to VPN using network-manager, while command line worksStart a VPN connection with PPTP protocol on command linestarting a docker service daemon breaks the vpn networkCan't connect to vpn with Network-managerVPN SSL Network Extender in FirefoxUsing Checkpoint VPN SSL Network Extender CLI with certificate

                                Cannot Extend partition with GParted The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election ResultsCan't increase partition size with GParted?GParted doesn't recognize the unallocated space after my current partitionWhat is the best way to add unallocated space located before to Ubuntu 12.04 partition with GParted live?I can't figure out how to extend my Arch home partition into free spaceGparted Linux Mint 18.1 issueTrying to extend but swap partition is showing as Unknown in Gparted, shows proper from fdiskRearrange partitions in gparted to extend a partitionUnable to extend partition even though unallocated space is next to it using GPartedAllocate free space to root partitiongparted: how to merge unallocated space with a partition

                                Marilyn Monroe Ny fiainany manokana | Jereo koa | Meny fitetezanafanitarana azy.