3

I an creating a bash array:

    for i in *.txt; do
    arr2+=$(printf "%s\n" "${arr[@]: 0: 1}  $arr[@]: 1: 1}")
done

echo "${arr2}"

The output is all on the same line ( when I use awk to get first column, only first element is returned).

How do I get each iteration of the for loop to put each new entry into the array on a newline?

brucezepplin
  • 9,202
  • 26
  • 76
  • 129

1 Answers1

6

As stated here: https://stackoverflow.com/a/5322980/4716013 be careful with $() that removed trailing new line! A way to preserve new line: use of "".

So that your command must be updated for example like this:

for i in *.txt; do
  tmp=$(printf "$i")
  arr2+="$tmp\n" # <--- here we preserve the new line!
done

echo -e "${arr2}" # option '-e' allow interpretation of the '\n'
Community
  • 1
  • 1
prodev_paris
  • 495
  • 1
  • 4
  • 17