So it would be a little tricky to make this work portably in sed
- you should be looking to cut
and/or paste
with some regex precursor generating their script in that context - and this is because sed
will always insert a \n
ewline before the output of a r
ead. Still, w/ GNU sed
:
sed '/First/{x;s/.*/cat file/e;H;x;s/\n//}' <<\IN
First
Second
Third
IN
That works by e
xecuting cat
every time it encounters your /First/
address. It does this in the h
old space (kind of - an alternate buffer anyway - because I ex
change them it actually happens in pattern space which used to be h
old space) so as to preserve the contents of the line matching First
and then appends cat
's output to your line and removes the intervening \n
ewline.
OUTPUT:
First[
{
"foo": "bar",
"baz": "biff",
"data": [
{
"a": 1945619,
"b": [
{
"c": 512665,
"d": "futz"
}
]
}
]
}
]
Second
Third
Now if you want the entire contents of the file to fit between two portions of a line that has to work a little differently because with the above command I just remove the trailing newline between the end of the matching line and the beginning of the file. Still, you can do this, too:
sed '/First/{s//&\n/;h
s/.*/{ cat file; echo .; }/e;G
s/\(.*\).\n\(.*\)\n/\2\1/
}' <<\IN
Third
Second
First Second Third
Third
Second
First Second Third
IN
That splits the line at the match with a \n
ewline character, saves it in h
old space, e
xecutes cat
- which replaces pattern space with its output - G
ets the contents of the hold space appended to our new pattern space following another \n
ewline character, and then rearranges on \n
ewline delimiters.
I do echo .
to preserve any trailing \n
ewline characters in file
- but if that is not your wish (and isn't very relevant to your example anyway) you can do without it and remove the first .
before .\n
in the following s///
ubstitution.
Just before the rearrange pattern space looks like this:
^cat's output - any number of newlines.*.\nmatch on First\nrest of match$
OUTPUT:
Third
Second
First[
{
"foo": "bar",
"baz": "biff",
"data": [
{
"a": 1945619,
"b": [
{
"c": 512665,
"d": "futz"
}
]
}
]
}
] Second Third
Third
Second
First[
{
"foo": "bar",
"baz": "biff",
"data": [
{
"a": 1945619,
"b": [
{
"c": 512665,
"d": "futz"
}
]
}
]
}
] Second Third
First
- duh. sorry. – mikeserv Dec 09 '14 at 22:05sed
but I just wanna make sure... – mikeserv Dec 09 '14 at 22:07