When you are happy with a solution that puts every <?
at the start of a line, you can combine tr
with sed
.
tr -d '\n' < inputfile| sed 's/<?/\n&/g;$s/$/\n/'
Explanation:
I use tr ... < inputfile
and not cat inputfile | tr ...
avoiding an additional cat
call.
The sed
command has 2 parts.
In s/<?/\n&/g
it will insert a newline and with &
it will insert the matched string (in this case always <?
, so it will only save one character).
With $s/$/\n/
a newline is appended at the end of the last line.
EDIT: When you only want newlines before <?
when you had them already,
you can use awk
:
awk '$1 ~ /^<\?/ {print} {printf("%s",$0)} END {print}'
Explanation:
Consider the newline as the start of the line, not the end. Then your question transposes into "write a newline when the line starts with <?
. You must escape the ?
and use ^
for the start of the line.
awk '$1 ~ /^<\?/ {print}'
Next print the line you read without a newline character.
And you want a newline at the end.