Victor Tan Victor Tan - 1 year ago 103
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`
echo $i
echo ${i}_NDVI

The result is:


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


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

Answer Source

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
  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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download