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 "{}\" \012\011\015" | tr "," "\012"
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 "\012" "%" | sed "s/%/; /g"
(newlines are converted to % by tr
, then sed
converts all % characters to "; " character pairs.)