Search code examples
bashvariablesparametersexpansion

How to remove empty lines from a string in bash using parameter expansion?


I have the following variable.

echo "|${VAR1}|"

which returns

|
ABC

XYZ|

How can I remove the empty lines, preserving line breaks and using parameter expansion? So that it would become

|ABC
XYZ|

p.s.: I know how to do it using pipe sed, but I would like to avoid the extra SED process:

VAR1=`echo "${VAR1}" | sed '/^\s*$/d'`

Solution

  • Remove the leading newlines, then replace any consecutive newlines with a single one.

    #! /bin/bash
    
    var='
    ABC
    
    XYZ'
    
    expected='ABC
    XYZ'
    
    shopt -s extglob
    var=${var##+($'\n')}
    var=${var//+($'\n')/$'\n'}
    [[ $var == $expected ]] && echo OK