1

What's wrong with below code to split text block by newline?

#!/bin/bash
txt="abcd
efg hijk lmn
opq
rst"

lines=${txt%$'\n'*}
for line in $lines; do
    echo $line
done

Current output is:

abcd
efg
hijk
lmn
opq

expected output:

abcd
efg hijk lmn
opq
rst
lucky1928
  • 8,708
  • 10
  • 43
  • 92
  • Use `mapfile -t arr <<< "$txt"` and then iterate the array. – anubhava Mar 07 '23 at 20:02
  • `for line in $lines` splits on `IFS`, which by default means whitespace. The easy fix would be to not assign the variable separately; `( IFS=$'\n'; for line in $txt; do echo "$line"; done )` where the parentheses create a subshell to ensure that the change to `IFS` is not persisted. But probably a better solution is to put the lines in an array, as suggested by @anubhava - or just `echo "$txt"` if all you want is to echo the lines, of course. – tripleee Mar 08 '23 at 05:56
  • @tripleee Great, but some bash (android) do not support " parentheses create a subshell ", any other way for such shell? – lucky1928 Mar 08 '23 at 14:10
  • Every remotely POSIX-compliant shell can fork itself. It's definitely not Bash if it lacks that functionality; it could not run other programs either if it wasn't able to run itself. A crude workaround is to save the original value of IFS and then restore it; `oldIFS=$IFS; for line in $txt; do echo "$line"; done; IFS=$oldIFS` – tripleee Mar 08 '23 at 14:52

0 Answers0