Don't use all upper case for non-exported variable names to avoid conflicting with exported and/or built in names. With GNU awk for the 3rd arg to match() and \S
shorthand for [^[:space:]]
:
$ example='-----BEGIN CERTIFICATE----- line1 line2 line3 -----END CERTIFICATE-----'
$ printf '%s\n' "$example" |
awk 'match($0,/^(\S+ \S+)(.*)(\S+ \S+)$/,a){gsub(/ /,ORS,a[2]); print a[1] a[2] a[3]}'
-----BEGIN CERTIFICATE-----
line1
line2
line3
-----END CERTIFICATE-----
The above script will work for any input. You should try to come up with input that scripts might fail on to be able to test any proposed solution against to see if it actually works or not as it's trivial to come up with a script that produces the expected output from one specific sample input and far harder to come up with a solution that works in all cases.
For instance, one important and obvious example to test with is:
$ example='-----BEGIN CERTIFICATE----- -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- -----END CERTIFICATE-----'
i.e. where within the 4-line certificate itself there just happens to coincidentally/unfortunately be these strings:
- line 1 =
-----BEGIN
- line 2 =
CERTIFICATE-----
- line 3 =
-----END
- line 4 =
CERTIFICATE-----
The output should be:
$ printf '%s\n' "$example" |
awk 'match($0,/^(\S+ \S+)(.*)(\S+ \S+)$/,a){gsub(/ /,ORS,a[2]); print a[1] a[2] a[3]}'
-----BEGIN CERTIFICATE-----
-----BEGIN
CERTIFICATE-----
-----END
CERTIFICATE-----
-----END CERTIFICATE-----
so if any proposed solution can't handle that correctly then don't use that solution.
None of the other currently posted answers handle it correctly:
Ravinder's awk:
$ printf '%s\n' "$example" |
awk '
match($0,/- .* -/){
val=substr($0,RSTART,RLENGTH)
gsub(/- | -/,"",val)
gsub(OFS,ORS,val)
print substr($0,1,RSTART) ORS val ORS substr($0,RSTART+RLENGTH-1)
}'
-----BEGIN CERTIFICATE-----
-----BEGIN
CERTIFICATE---------END
CERTIFICATE-----
-----END CERTIFICATE-----
saichovsky's seds plus pipe:
$ printf '%s\n' "$example" |
sed 's/- /-\n/g; s/ -/\n-/g' | sed '/CERTIFICATE/! s/ /\n/g'
-----BEGIN CERTIFICATE-----
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
-----END CERTIFICATE-----
anubhava's perl:
$ perl -pe 's/(?:BEGIN|END) CERTIFICATE(*SKIP)(*F)|\h+/\n/g' <<< "$example"
-----BEGIN CERTIFICATE-----
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
-----END CERTIFICATE-----