Multiple sed commands in Bash











up vote
3
down vote

favorite
3












I have a a file usernames and passwords in JSON format that I want to convert to process.



I have used sed in different commands to process it but what I would like to know is how to lump all three commands into one for the future.



Original format



    { "user.name1" : "hashed_password",
"user.name2" : "hashed_password" }


Desired output



user.name:hashed_password


These are the commands I ran, however I have been unable to chain them together using either piping or simply concatenating them where I get an error, sed: -e expression #1, char 8: unknown option to 's'.



Offending command...



sed -i 's/"//g/s/,/n/g/s//g' input_file 
sed: -e expression #1, char 8: unknown option to `s'


How could the below commands be concatenated into one?



Commands
Remove double quotes



sed -i 's/"//g' input_file



Replace comma with new line



sed -i 's/,/n/g' input_file



Remove whitespace



sed -i 's/s//g input_file










share|improve this question




























    up vote
    3
    down vote

    favorite
    3












    I have a a file usernames and passwords in JSON format that I want to convert to process.



    I have used sed in different commands to process it but what I would like to know is how to lump all three commands into one for the future.



    Original format



        { "user.name1" : "hashed_password",
    "user.name2" : "hashed_password" }


    Desired output



    user.name:hashed_password


    These are the commands I ran, however I have been unable to chain them together using either piping or simply concatenating them where I get an error, sed: -e expression #1, char 8: unknown option to 's'.



    Offending command...



    sed -i 's/"//g/s/,/n/g/s//g' input_file 
    sed: -e expression #1, char 8: unknown option to `s'


    How could the below commands be concatenated into one?



    Commands
    Remove double quotes



    sed -i 's/"//g' input_file



    Replace comma with new line



    sed -i 's/,/n/g' input_file



    Remove whitespace



    sed -i 's/s//g input_file










    share|improve this question


























      up vote
      3
      down vote

      favorite
      3









      up vote
      3
      down vote

      favorite
      3






      3





      I have a a file usernames and passwords in JSON format that I want to convert to process.



      I have used sed in different commands to process it but what I would like to know is how to lump all three commands into one for the future.



      Original format



          { "user.name1" : "hashed_password",
      "user.name2" : "hashed_password" }


      Desired output



      user.name:hashed_password


      These are the commands I ran, however I have been unable to chain them together using either piping or simply concatenating them where I get an error, sed: -e expression #1, char 8: unknown option to 's'.



      Offending command...



      sed -i 's/"//g/s/,/n/g/s//g' input_file 
      sed: -e expression #1, char 8: unknown option to `s'


      How could the below commands be concatenated into one?



      Commands
      Remove double quotes



      sed -i 's/"//g' input_file



      Replace comma with new line



      sed -i 's/,/n/g' input_file



      Remove whitespace



      sed -i 's/s//g input_file










      share|improve this question















      I have a a file usernames and passwords in JSON format that I want to convert to process.



      I have used sed in different commands to process it but what I would like to know is how to lump all three commands into one for the future.



      Original format



          { "user.name1" : "hashed_password",
      "user.name2" : "hashed_password" }


      Desired output



      user.name:hashed_password


      These are the commands I ran, however I have been unable to chain them together using either piping or simply concatenating them where I get an error, sed: -e expression #1, char 8: unknown option to 's'.



      Offending command...



      sed -i 's/"//g/s/,/n/g/s//g' input_file 
      sed: -e expression #1, char 8: unknown option to `s'


      How could the below commands be concatenated into one?



      Commands
      Remove double quotes



      sed -i 's/"//g' input_file



      Replace comma with new line



      sed -i 's/,/n/g' input_file



      Remove whitespace



      sed -i 's/s//g input_file







      linux bash sed






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 4 at 11:53

























      asked Dec 4 at 11:43









      Rich C

      1357




      1357






















          5 Answers
          5






          active

          oldest

          votes

















          up vote
          16
          down vote



          accepted










          To put multiple sed commands in a single "script", you can use multiple -e flags (which is portable):



          sed -i -e 's/"//g' -e 's/,/n/g' -e 's/s//g' input_file


          Or the semicolon delimiter (which is not available on all implementations):



          sed -i 's/"//g;s/,/n/g;s/s//g' input_file


          You'll need to add handling for the braces too - {}...





          Having said this, to parse and handle JSON properly, you shouldn't really use sed... perhaps try jq!



          jq -r 'keys as $k | "($k):(.[$k])"' input_file


          Output:



          user.name1:hashed_password
          user.name2:hashed_password




          • keys as $k will iterate through each key storing its value in $k


            • i.e: user.name1, user.name2




          • "($k):(.[$k])" will form a string, substituting in $k and .[$k]

          • Using -r removes the quotes from output strings (raw mode)




          Using sed to process JSON is going to open you up to all sorts of issues... for example, how would you deal with the following (completely valid JSON) input?



          {
          "user.name1" :
          "hashed_password",
          "user.name2" :
          "hashed_password"
          }





          share|improve this answer






























            up vote
            3
            down vote













            When you're dealing with standardised input like JSON, it's generally better to use a proper parser rather than regex. For example, you'll correctly convert any escape sequences (though that may not be possible with your particular input data!).



            Unfortunately, there's no great tools for dealing with JSON within coreutils. Attie's provided jq as a decent option if you are free to install packages.



            If you're unable to install additional packages, it's not particularly difficult in Python. Take this script for example:



            import json,sys
            for (k, v) in json.load(sys.stdin):
            print(k + ":" + v)


            Which can be compressed into one line:



            cat inputdata | python -c 'import json,sys;print("n".join((k + ":" + v) for (k, v) in json.load(sys.stdin).items()))'





            share|improve this answer




























              up vote
              0
              down vote













              For the simple character deletion you're doing in these sed commands I would instead recommend you use tr, whose sole purpose is to delete, squeeze, or replace individual characters, including newlines (sed is based on regex's, which normally rely on newlines as buffer separators, so using sed to modify newlines is tricky). I think this tr command does everything you're looking for:



              cat json_filename | tr -d "{}" 121115" | tr "," "12"


              The first tr command deletes all curly braces, double-quotes, spaces, carriage returns (octal 012, ascii 10), tabs (octal 011, ascii 9, and linefeed (octal 015, ascii 13) characters. The second tr command replaces all commas with carriage returns. As long as your JSON file's variable names and values don't contain commas, these commands would allow you to avoid needing a dedicated JSON parser.



              That said, if you have a set of sed commands that each work independently, combining them may be most easily accomplished using the "-f" sed option to read the separate commands from a file. You just put the s/.../.../g strings into a file, each string on its own line, then specify that filename after the "-f" option. For example, if the three sed commands you listed are satisfactory, you could put them into a file named "json.convert.sed" that simply contained this:



              s/"//g 
              s/,/n/g
              s/s//g


              Then you would invoke sed with this command file using:



              sed -f json.convert.sed


              That said, these sed commands don't work for me to accomplish what you want, and I'm not sure you can ever get sed to modify newline characters. This is because sed is based on the old "ed" line editor, designed to edit single lines at a time (a "script"-able version of it), so each line of input is "parsed" using newlines as the delimiters, then the line (without the newline) is passed to the editing engine, the editing commands are applied, then the edited line is output with a newline. Then the loop repeats. I've only ever been able to use sed to modify newline by first changing the newlines to some distinct character (that doesn't otherwise appear in the input) using tr. There's no point to using tr this way if all you want to do is delete newlines, since tr will do that for you. But if, for instance, you wanted to convert newlines to semicolons with a trailing space, one way to do that would be:



              cat input_file | tr "12" "%" | sed "s/%/; /g"


              (newlines are converted to % by tr, then sed converts all % characters to "; " character pairs.)






              share|improve this answer






























                up vote
                0
                down vote













                Sed can handle multi-line editing, but I agree with Attie and Bob, parse json with sed regex can become a nightmare.



                sed -nr '/{/ b Load ; d
                : Load
                /}/ b Edit ; N ; b Load
                : Edit ; s/[^"]+"([^"]+)"[^"]+"([^"]+)"(.*)/1:2n3/ ; t Print ; d
                : Print ; P ; s/[^n]+n// ; t Edit' <<'eof'
                {
                "user.name1" :
                "hashed_password1",
                "user.name2" :
                "hashed_password2"
                }
                { "user.name3" : "hashed_password3",
                "user.name4" : "hashed_password4" }

                { "user.name5":"hashed_password5"}
                eof

                user.name1:hashed_password1
                user.name2:hashed_password2
                user.name3:hashed_password3
                user.name4:hashed_password4
                user.name5:hashed_password5





                share|improve this answer




























                  up vote
                  -1
                  down vote













                  You could combine it like this:



                  sed -i 's/"//g;s/,/n/g;s/s//g' input_file



                  You forgot to add the removal of {}. So you probably want:



                  sed -i 's/"//g;s/,/n/g;s/s//g;s/{//g;s/}//g' input_file






                  share|improve this answer























                    Your Answer








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

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

                    function createEditor() {
                    StackExchange.prepareEditor({
                    heartbeatType: 'answer',
                    autoActivateHeartbeat: false,
                    convertImagesToLinks: true,
                    noModals: true,
                    showLowRepImageUploadWarning: true,
                    reputationToPostImages: 10,
                    bindNavPrevention: true,
                    postfix: "",
                    imageUploader: {
                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/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%2fsuperuser.com%2fquestions%2f1380672%2fmultiple-sed-commands-in-bash%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    5 Answers
                    5






                    active

                    oldest

                    votes








                    5 Answers
                    5






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes








                    up vote
                    16
                    down vote



                    accepted










                    To put multiple sed commands in a single "script", you can use multiple -e flags (which is portable):



                    sed -i -e 's/"//g' -e 's/,/n/g' -e 's/s//g' input_file


                    Or the semicolon delimiter (which is not available on all implementations):



                    sed -i 's/"//g;s/,/n/g;s/s//g' input_file


                    You'll need to add handling for the braces too - {}...





                    Having said this, to parse and handle JSON properly, you shouldn't really use sed... perhaps try jq!



                    jq -r 'keys as $k | "($k):(.[$k])"' input_file


                    Output:



                    user.name1:hashed_password
                    user.name2:hashed_password




                    • keys as $k will iterate through each key storing its value in $k


                      • i.e: user.name1, user.name2




                    • "($k):(.[$k])" will form a string, substituting in $k and .[$k]

                    • Using -r removes the quotes from output strings (raw mode)




                    Using sed to process JSON is going to open you up to all sorts of issues... for example, how would you deal with the following (completely valid JSON) input?



                    {
                    "user.name1" :
                    "hashed_password",
                    "user.name2" :
                    "hashed_password"
                    }





                    share|improve this answer



























                      up vote
                      16
                      down vote



                      accepted










                      To put multiple sed commands in a single "script", you can use multiple -e flags (which is portable):



                      sed -i -e 's/"//g' -e 's/,/n/g' -e 's/s//g' input_file


                      Or the semicolon delimiter (which is not available on all implementations):



                      sed -i 's/"//g;s/,/n/g;s/s//g' input_file


                      You'll need to add handling for the braces too - {}...





                      Having said this, to parse and handle JSON properly, you shouldn't really use sed... perhaps try jq!



                      jq -r 'keys as $k | "($k):(.[$k])"' input_file


                      Output:



                      user.name1:hashed_password
                      user.name2:hashed_password




                      • keys as $k will iterate through each key storing its value in $k


                        • i.e: user.name1, user.name2




                      • "($k):(.[$k])" will form a string, substituting in $k and .[$k]

                      • Using -r removes the quotes from output strings (raw mode)




                      Using sed to process JSON is going to open you up to all sorts of issues... for example, how would you deal with the following (completely valid JSON) input?



                      {
                      "user.name1" :
                      "hashed_password",
                      "user.name2" :
                      "hashed_password"
                      }





                      share|improve this answer

























                        up vote
                        16
                        down vote



                        accepted







                        up vote
                        16
                        down vote



                        accepted






                        To put multiple sed commands in a single "script", you can use multiple -e flags (which is portable):



                        sed -i -e 's/"//g' -e 's/,/n/g' -e 's/s//g' input_file


                        Or the semicolon delimiter (which is not available on all implementations):



                        sed -i 's/"//g;s/,/n/g;s/s//g' input_file


                        You'll need to add handling for the braces too - {}...





                        Having said this, to parse and handle JSON properly, you shouldn't really use sed... perhaps try jq!



                        jq -r 'keys as $k | "($k):(.[$k])"' input_file


                        Output:



                        user.name1:hashed_password
                        user.name2:hashed_password




                        • keys as $k will iterate through each key storing its value in $k


                          • i.e: user.name1, user.name2




                        • "($k):(.[$k])" will form a string, substituting in $k and .[$k]

                        • Using -r removes the quotes from output strings (raw mode)




                        Using sed to process JSON is going to open you up to all sorts of issues... for example, how would you deal with the following (completely valid JSON) input?



                        {
                        "user.name1" :
                        "hashed_password",
                        "user.name2" :
                        "hashed_password"
                        }





                        share|improve this answer














                        To put multiple sed commands in a single "script", you can use multiple -e flags (which is portable):



                        sed -i -e 's/"//g' -e 's/,/n/g' -e 's/s//g' input_file


                        Or the semicolon delimiter (which is not available on all implementations):



                        sed -i 's/"//g;s/,/n/g;s/s//g' input_file


                        You'll need to add handling for the braces too - {}...





                        Having said this, to parse and handle JSON properly, you shouldn't really use sed... perhaps try jq!



                        jq -r 'keys as $k | "($k):(.[$k])"' input_file


                        Output:



                        user.name1:hashed_password
                        user.name2:hashed_password




                        • keys as $k will iterate through each key storing its value in $k


                          • i.e: user.name1, user.name2




                        • "($k):(.[$k])" will form a string, substituting in $k and .[$k]

                        • Using -r removes the quotes from output strings (raw mode)




                        Using sed to process JSON is going to open you up to all sorts of issues... for example, how would you deal with the following (completely valid JSON) input?



                        {
                        "user.name1" :
                        "hashed_password",
                        "user.name2" :
                        "hashed_password"
                        }






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Dec 5 at 21:12

























                        answered Dec 4 at 12:11









                        Attie

                        10.9k32444




                        10.9k32444
























                            up vote
                            3
                            down vote













                            When you're dealing with standardised input like JSON, it's generally better to use a proper parser rather than regex. For example, you'll correctly convert any escape sequences (though that may not be possible with your particular input data!).



                            Unfortunately, there's no great tools for dealing with JSON within coreutils. Attie's provided jq as a decent option if you are free to install packages.



                            If you're unable to install additional packages, it's not particularly difficult in Python. Take this script for example:



                            import json,sys
                            for (k, v) in json.load(sys.stdin):
                            print(k + ":" + v)


                            Which can be compressed into one line:



                            cat inputdata | python -c 'import json,sys;print("n".join((k + ":" + v) for (k, v) in json.load(sys.stdin).items()))'





                            share|improve this answer

























                              up vote
                              3
                              down vote













                              When you're dealing with standardised input like JSON, it's generally better to use a proper parser rather than regex. For example, you'll correctly convert any escape sequences (though that may not be possible with your particular input data!).



                              Unfortunately, there's no great tools for dealing with JSON within coreutils. Attie's provided jq as a decent option if you are free to install packages.



                              If you're unable to install additional packages, it's not particularly difficult in Python. Take this script for example:



                              import json,sys
                              for (k, v) in json.load(sys.stdin):
                              print(k + ":" + v)


                              Which can be compressed into one line:



                              cat inputdata | python -c 'import json,sys;print("n".join((k + ":" + v) for (k, v) in json.load(sys.stdin).items()))'





                              share|improve this answer























                                up vote
                                3
                                down vote










                                up vote
                                3
                                down vote









                                When you're dealing with standardised input like JSON, it's generally better to use a proper parser rather than regex. For example, you'll correctly convert any escape sequences (though that may not be possible with your particular input data!).



                                Unfortunately, there's no great tools for dealing with JSON within coreutils. Attie's provided jq as a decent option if you are free to install packages.



                                If you're unable to install additional packages, it's not particularly difficult in Python. Take this script for example:



                                import json,sys
                                for (k, v) in json.load(sys.stdin):
                                print(k + ":" + v)


                                Which can be compressed into one line:



                                cat inputdata | python -c 'import json,sys;print("n".join((k + ":" + v) for (k, v) in json.load(sys.stdin).items()))'





                                share|improve this answer












                                When you're dealing with standardised input like JSON, it's generally better to use a proper parser rather than regex. For example, you'll correctly convert any escape sequences (though that may not be possible with your particular input data!).



                                Unfortunately, there's no great tools for dealing with JSON within coreutils. Attie's provided jq as a decent option if you are free to install packages.



                                If you're unable to install additional packages, it's not particularly difficult in Python. Take this script for example:



                                import json,sys
                                for (k, v) in json.load(sys.stdin):
                                print(k + ":" + v)


                                Which can be compressed into one line:



                                cat inputdata | python -c 'import json,sys;print("n".join((k + ":" + v) for (k, v) in json.load(sys.stdin).items()))'






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Dec 4 at 15:56









                                Bob

                                45.2k20137171




                                45.2k20137171






















                                    up vote
                                    0
                                    down vote













                                    For the simple character deletion you're doing in these sed commands I would instead recommend you use tr, whose sole purpose is to delete, squeeze, or replace individual characters, including newlines (sed is based on regex's, which normally rely on newlines as buffer separators, so using sed to modify newlines is tricky). I think this tr command does everything you're looking for:



                                    cat json_filename | tr -d "{}" 121115" | tr "," "12"


                                    The first tr command deletes all curly braces, double-quotes, spaces, carriage returns (octal 012, ascii 10), tabs (octal 011, ascii 9, and linefeed (octal 015, ascii 13) characters. The second tr command replaces all commas with carriage returns. As long as your JSON file's variable names and values don't contain commas, these commands would allow you to avoid needing a dedicated JSON parser.



                                    That said, if you have a set of sed commands that each work independently, combining them may be most easily accomplished using the "-f" sed option to read the separate commands from a file. You just put the s/.../.../g strings into a file, each string on its own line, then specify that filename after the "-f" option. For example, if the three sed commands you listed are satisfactory, you could put them into a file named "json.convert.sed" that simply contained this:



                                    s/"//g 
                                    s/,/n/g
                                    s/s//g


                                    Then you would invoke sed with this command file using:



                                    sed -f json.convert.sed


                                    That said, these sed commands don't work for me to accomplish what you want, and I'm not sure you can ever get sed to modify newline characters. This is because sed is based on the old "ed" line editor, designed to edit single lines at a time (a "script"-able version of it), so each line of input is "parsed" using newlines as the delimiters, then the line (without the newline) is passed to the editing engine, the editing commands are applied, then the edited line is output with a newline. Then the loop repeats. I've only ever been able to use sed to modify newline by first changing the newlines to some distinct character (that doesn't otherwise appear in the input) using tr. There's no point to using tr this way if all you want to do is delete newlines, since tr will do that for you. But if, for instance, you wanted to convert newlines to semicolons with a trailing space, one way to do that would be:



                                    cat input_file | tr "12" "%" | sed "s/%/; /g"


                                    (newlines are converted to % by tr, then sed converts all % characters to "; " character pairs.)






                                    share|improve this answer



























                                      up vote
                                      0
                                      down vote













                                      For the simple character deletion you're doing in these sed commands I would instead recommend you use tr, whose sole purpose is to delete, squeeze, or replace individual characters, including newlines (sed is based on regex's, which normally rely on newlines as buffer separators, so using sed to modify newlines is tricky). I think this tr command does everything you're looking for:



                                      cat json_filename | tr -d "{}" 121115" | tr "," "12"


                                      The first tr command deletes all curly braces, double-quotes, spaces, carriage returns (octal 012, ascii 10), tabs (octal 011, ascii 9, and linefeed (octal 015, ascii 13) characters. The second tr command replaces all commas with carriage returns. As long as your JSON file's variable names and values don't contain commas, these commands would allow you to avoid needing a dedicated JSON parser.



                                      That said, if you have a set of sed commands that each work independently, combining them may be most easily accomplished using the "-f" sed option to read the separate commands from a file. You just put the s/.../.../g strings into a file, each string on its own line, then specify that filename after the "-f" option. For example, if the three sed commands you listed are satisfactory, you could put them into a file named "json.convert.sed" that simply contained this:



                                      s/"//g 
                                      s/,/n/g
                                      s/s//g


                                      Then you would invoke sed with this command file using:



                                      sed -f json.convert.sed


                                      That said, these sed commands don't work for me to accomplish what you want, and I'm not sure you can ever get sed to modify newline characters. This is because sed is based on the old "ed" line editor, designed to edit single lines at a time (a "script"-able version of it), so each line of input is "parsed" using newlines as the delimiters, then the line (without the newline) is passed to the editing engine, the editing commands are applied, then the edited line is output with a newline. Then the loop repeats. I've only ever been able to use sed to modify newline by first changing the newlines to some distinct character (that doesn't otherwise appear in the input) using tr. There's no point to using tr this way if all you want to do is delete newlines, since tr will do that for you. But if, for instance, you wanted to convert newlines to semicolons with a trailing space, one way to do that would be:



                                      cat input_file | tr "12" "%" | sed "s/%/; /g"


                                      (newlines are converted to % by tr, then sed converts all % characters to "; " character pairs.)






                                      share|improve this answer

























                                        up vote
                                        0
                                        down vote










                                        up vote
                                        0
                                        down vote









                                        For the simple character deletion you're doing in these sed commands I would instead recommend you use tr, whose sole purpose is to delete, squeeze, or replace individual characters, including newlines (sed is based on regex's, which normally rely on newlines as buffer separators, so using sed to modify newlines is tricky). I think this tr command does everything you're looking for:



                                        cat json_filename | tr -d "{}" 121115" | tr "," "12"


                                        The first tr command deletes all curly braces, double-quotes, spaces, carriage returns (octal 012, ascii 10), tabs (octal 011, ascii 9, and linefeed (octal 015, ascii 13) characters. The second tr command replaces all commas with carriage returns. As long as your JSON file's variable names and values don't contain commas, these commands would allow you to avoid needing a dedicated JSON parser.



                                        That said, if you have a set of sed commands that each work independently, combining them may be most easily accomplished using the "-f" sed option to read the separate commands from a file. You just put the s/.../.../g strings into a file, each string on its own line, then specify that filename after the "-f" option. For example, if the three sed commands you listed are satisfactory, you could put them into a file named "json.convert.sed" that simply contained this:



                                        s/"//g 
                                        s/,/n/g
                                        s/s//g


                                        Then you would invoke sed with this command file using:



                                        sed -f json.convert.sed


                                        That said, these sed commands don't work for me to accomplish what you want, and I'm not sure you can ever get sed to modify newline characters. This is because sed is based on the old "ed" line editor, designed to edit single lines at a time (a "script"-able version of it), so each line of input is "parsed" using newlines as the delimiters, then the line (without the newline) is passed to the editing engine, the editing commands are applied, then the edited line is output with a newline. Then the loop repeats. I've only ever been able to use sed to modify newline by first changing the newlines to some distinct character (that doesn't otherwise appear in the input) using tr. There's no point to using tr this way if all you want to do is delete newlines, since tr will do that for you. But if, for instance, you wanted to convert newlines to semicolons with a trailing space, one way to do that would be:



                                        cat input_file | tr "12" "%" | sed "s/%/; /g"


                                        (newlines are converted to % by tr, then sed converts all % characters to "; " character pairs.)






                                        share|improve this answer














                                        For the simple character deletion you're doing in these sed commands I would instead recommend you use tr, whose sole purpose is to delete, squeeze, or replace individual characters, including newlines (sed is based on regex's, which normally rely on newlines as buffer separators, so using sed to modify newlines is tricky). I think this tr command does everything you're looking for:



                                        cat json_filename | tr -d "{}" 121115" | tr "," "12"


                                        The first tr command deletes all curly braces, double-quotes, spaces, carriage returns (octal 012, ascii 10), tabs (octal 011, ascii 9, and linefeed (octal 015, ascii 13) characters. The second tr command replaces all commas with carriage returns. As long as your JSON file's variable names and values don't contain commas, these commands would allow you to avoid needing a dedicated JSON parser.



                                        That said, if you have a set of sed commands that each work independently, combining them may be most easily accomplished using the "-f" sed option to read the separate commands from a file. You just put the s/.../.../g strings into a file, each string on its own line, then specify that filename after the "-f" option. For example, if the three sed commands you listed are satisfactory, you could put them into a file named "json.convert.sed" that simply contained this:



                                        s/"//g 
                                        s/,/n/g
                                        s/s//g


                                        Then you would invoke sed with this command file using:



                                        sed -f json.convert.sed


                                        That said, these sed commands don't work for me to accomplish what you want, and I'm not sure you can ever get sed to modify newline characters. This is because sed is based on the old "ed" line editor, designed to edit single lines at a time (a "script"-able version of it), so each line of input is "parsed" using newlines as the delimiters, then the line (without the newline) is passed to the editing engine, the editing commands are applied, then the edited line is output with a newline. Then the loop repeats. I've only ever been able to use sed to modify newline by first changing the newlines to some distinct character (that doesn't otherwise appear in the input) using tr. There's no point to using tr this way if all you want to do is delete newlines, since tr will do that for you. But if, for instance, you wanted to convert newlines to semicolons with a trailing space, one way to do that would be:



                                        cat input_file | tr "12" "%" | sed "s/%/; /g"


                                        (newlines are converted to % by tr, then sed converts all % characters to "; " character pairs.)







                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Dec 7 at 23:19









                                        Rey Juna

                                        5439




                                        5439










                                        answered Dec 7 at 21:39









                                        J. Hansen

                                        11




                                        11






















                                            up vote
                                            0
                                            down vote













                                            Sed can handle multi-line editing, but I agree with Attie and Bob, parse json with sed regex can become a nightmare.



                                            sed -nr '/{/ b Load ; d
                                            : Load
                                            /}/ b Edit ; N ; b Load
                                            : Edit ; s/[^"]+"([^"]+)"[^"]+"([^"]+)"(.*)/1:2n3/ ; t Print ; d
                                            : Print ; P ; s/[^n]+n// ; t Edit' <<'eof'
                                            {
                                            "user.name1" :
                                            "hashed_password1",
                                            "user.name2" :
                                            "hashed_password2"
                                            }
                                            { "user.name3" : "hashed_password3",
                                            "user.name4" : "hashed_password4" }

                                            { "user.name5":"hashed_password5"}
                                            eof

                                            user.name1:hashed_password1
                                            user.name2:hashed_password2
                                            user.name3:hashed_password3
                                            user.name4:hashed_password4
                                            user.name5:hashed_password5





                                            share|improve this answer

























                                              up vote
                                              0
                                              down vote













                                              Sed can handle multi-line editing, but I agree with Attie and Bob, parse json with sed regex can become a nightmare.



                                              sed -nr '/{/ b Load ; d
                                              : Load
                                              /}/ b Edit ; N ; b Load
                                              : Edit ; s/[^"]+"([^"]+)"[^"]+"([^"]+)"(.*)/1:2n3/ ; t Print ; d
                                              : Print ; P ; s/[^n]+n// ; t Edit' <<'eof'
                                              {
                                              "user.name1" :
                                              "hashed_password1",
                                              "user.name2" :
                                              "hashed_password2"
                                              }
                                              { "user.name3" : "hashed_password3",
                                              "user.name4" : "hashed_password4" }

                                              { "user.name5":"hashed_password5"}
                                              eof

                                              user.name1:hashed_password1
                                              user.name2:hashed_password2
                                              user.name3:hashed_password3
                                              user.name4:hashed_password4
                                              user.name5:hashed_password5





                                              share|improve this answer























                                                up vote
                                                0
                                                down vote










                                                up vote
                                                0
                                                down vote









                                                Sed can handle multi-line editing, but I agree with Attie and Bob, parse json with sed regex can become a nightmare.



                                                sed -nr '/{/ b Load ; d
                                                : Load
                                                /}/ b Edit ; N ; b Load
                                                : Edit ; s/[^"]+"([^"]+)"[^"]+"([^"]+)"(.*)/1:2n3/ ; t Print ; d
                                                : Print ; P ; s/[^n]+n// ; t Edit' <<'eof'
                                                {
                                                "user.name1" :
                                                "hashed_password1",
                                                "user.name2" :
                                                "hashed_password2"
                                                }
                                                { "user.name3" : "hashed_password3",
                                                "user.name4" : "hashed_password4" }

                                                { "user.name5":"hashed_password5"}
                                                eof

                                                user.name1:hashed_password1
                                                user.name2:hashed_password2
                                                user.name3:hashed_password3
                                                user.name4:hashed_password4
                                                user.name5:hashed_password5





                                                share|improve this answer












                                                Sed can handle multi-line editing, but I agree with Attie and Bob, parse json with sed regex can become a nightmare.



                                                sed -nr '/{/ b Load ; d
                                                : Load
                                                /}/ b Edit ; N ; b Load
                                                : Edit ; s/[^"]+"([^"]+)"[^"]+"([^"]+)"(.*)/1:2n3/ ; t Print ; d
                                                : Print ; P ; s/[^n]+n// ; t Edit' <<'eof'
                                                {
                                                "user.name1" :
                                                "hashed_password1",
                                                "user.name2" :
                                                "hashed_password2"
                                                }
                                                { "user.name3" : "hashed_password3",
                                                "user.name4" : "hashed_password4" }

                                                { "user.name5":"hashed_password5"}
                                                eof

                                                user.name1:hashed_password1
                                                user.name2:hashed_password2
                                                user.name3:hashed_password3
                                                user.name4:hashed_password4
                                                user.name5:hashed_password5






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Dec 8 at 23:50









                                                Paulo

                                                49628




                                                49628






















                                                    up vote
                                                    -1
                                                    down vote













                                                    You could combine it like this:



                                                    sed -i 's/"//g;s/,/n/g;s/s//g' input_file



                                                    You forgot to add the removal of {}. So you probably want:



                                                    sed -i 's/"//g;s/,/n/g;s/s//g;s/{//g;s/}//g' input_file






                                                    share|improve this answer



























                                                      up vote
                                                      -1
                                                      down vote













                                                      You could combine it like this:



                                                      sed -i 's/"//g;s/,/n/g;s/s//g' input_file



                                                      You forgot to add the removal of {}. So you probably want:



                                                      sed -i 's/"//g;s/,/n/g;s/s//g;s/{//g;s/}//g' input_file






                                                      share|improve this answer

























                                                        up vote
                                                        -1
                                                        down vote










                                                        up vote
                                                        -1
                                                        down vote









                                                        You could combine it like this:



                                                        sed -i 's/"//g;s/,/n/g;s/s//g' input_file



                                                        You forgot to add the removal of {}. So you probably want:



                                                        sed -i 's/"//g;s/,/n/g;s/s//g;s/{//g;s/}//g' input_file






                                                        share|improve this answer














                                                        You could combine it like this:



                                                        sed -i 's/"//g;s/,/n/g;s/s//g' input_file



                                                        You forgot to add the removal of {}. So you probably want:



                                                        sed -i 's/"//g;s/,/n/g;s/s//g;s/{//g;s/}//g' input_file







                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Dec 4 at 12:25

























                                                        answered Dec 4 at 12:06









                                                        Eloy

                                                        465




                                                        465






























                                                            draft saved

                                                            draft discarded




















































                                                            Thanks for contributing an answer to Super User!


                                                            • 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.





                                                            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                            Please pay close attention to the following guidance:


                                                            • 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%2fsuperuser.com%2fquestions%2f1380672%2fmultiple-sed-commands-in-bash%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

                                                            Ellipse (mathématiques)

                                                            Quarter-circle Tiles

                                                            Mont Emei