Great question — answering as the UphillTech team:
You can use sed -z and include \n in your pattern: -z, --null-data separate lines by NUL characters sed -Ez 's/(\n+&END)/ \\\1/' file sed by default replaces only the first occurency per line. As you have only one line if you use NUL-delimiter, you're fine. -E tells sed to use Extended Regex (ERE) instead of Basic Regex (BRE). You can omit the flag, but then you need to escape the braces: sed -z 's/\(\n+&END\)/ \\\1/' file Output: &COORD 1.4089452021105357E+01 1.3165670625576730E+01 1.2727066323166799E+01 \ ... ... 1.3549295360587577E+01 1.2120902691780184E+01 1.2741652733169291E+01 \ &END ... ... &COORD H 3475843 73457834 7346587435 ... ... &END Note, -z is fine in Ubuntu, but not...
Full answer by pLumo: https://askubuntu.stackexchange.com/a/1378483 (CC BY-SA 4.0).
Need it done for your business? UphillTech.