1

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'`

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

read the lines of the variable into an array, and remove the empty elements

var1=$'\nABC\n\nXYZ'
mapfile -t arr <<<"$var1"

declare -p arr                  # => declare -a arr=([0]="" [1]="ABC" [2]="" [3]="XYZ")

for ((i = ${#arr[@]} - 1; i >= 0; i--)); do
    [[ -z ${arr[i]} ]] && unset "arr[i]"
done

declare -p arr                  # => declare -a arr=([1]="ABC" [3]="XYZ")

(IFS=$'\n'; echo "|${arr[*]}|")  # in a subshell for temporary IFS setting
|ABC
XYZ|

2 Comments

for i in "${!arr[@]}" would also work, as that dumps all the indices at once before the loop starts.
Holy cow, what a mess. I invite you to just edit it next time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.