0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answering! I tried your approach, but the result is the same as the original.
I think the issue is probably with the line endings in your input file; I've added to my answer.

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.