Salvio
Salvio

Reputation: 100

Bash doesn't respect newline in command substitution with cat

Supposing we have a file list.txt:

line 1
line 2

if I use this:

for line in $(cat list.txt)
do 
echo $line"_"
done

Even if I do:

OLD_IFS=$IFS
$IFS='$'

I get:

line1
line2_

and not:

line1_
line2_

How can I solve the problem?

Upvotes: 0

Views: 257

Answers (1)

that other guy
that other guy

Reputation: 123490

Ignoring your incorrect assignment $IFS='$', $ does not mean newline, linefeed or end-of-line. It means literal dollar sign.

To assign a line feed, use

IFS=$'\n'

However, do not attempt to use this to iterate over lines. Instead, use a while read loop, which will not expand globs or collapse empty lines:

while IFS= read -r line
do
  echo "${line}_"
done < file

or with similar benefits, read the lines into an array with mapfile:

mapfile -t lines < file
for line in "${lines[@]}"
do
  echo "${line}_"
done

Upvotes: 2

Related Questions