Victor Tan Victor Tan - 1 month ago 6
Bash Question

Concatenate string in a loop of shell script

I want to concatenate a suffix to a string in a loop of shell script, but the result makes me confused. The shell script is as follows:

for i in `cat IMAGElist.txt`
do
echo $i
echo ${i}_NDVI
done


The result is:

LT51240392010131BKT01
_NDVI40392010131BKT01
LT51240392010163BKT01
_NDVI40392010163BKT01
...


The front five chars was replaced with "_NDVI".
But the expected result should be:

LT51240392010131BKT01
LT51240392010131BKT01_NDVI
LT51240392010163BKT01
LT51240392010163BKT01_NDVI
...


I think the method for string concatenation is right if not in the loop. I don't know why this result is produced?

Answer

It looks as though your file may contain Windows-style line endings (carriage return + line feed), so you should convert them to UNIX-style ones. A simple way to do this is with the tool dos2unix.

Don't use for to read lines of a text file:

while read -r line
do
  echo "$line"
  echo "${line}_NDVI"
done < IMAGElist.txt

Note that you can achieve this result more efficiently with tools designed to process text, such as awk or sed.

Comments