shell: strange string concatenation behavior [duplicate]

旧巷老猫 提交于 2020-05-09 10:43:11

问题


I write a scipt like this:

#!/bin/bash
while read line
do
  echo line ${line}
  pdbfile=${line}.pdb  
  echo pdbfile ${pdbfile}
done < myfile

The result is:

line pdb8mhtA
.pdbfile pdb8mhtA

While it is supposed to be

line pdb8mhtA
pdbfile pdb8mhtA.pdb

What's wrong with this? Why the string concatenation does not work? And why the strange dot at the beginning of the line?
I replace with pdbfile=${line}'.pdb'. That does not change the result.


回答1:


The "string goes to the beginning of the line" is symptomatic of a carriage return in your $line that you can among many other ways remove with a tr pipe to your file:

while IFS= read -r line
do
  echo "line ${line}"
  pdbfile=${line}.pdb  
  echo "pdbfile ${pdbfile}"
done < <(tr -d '\r' <file)



回答2:


I've tried your script and it works fine for me:

./testConcat
line pdb8mhtA
pdbfile pdb8mhtA.pdb

btw you could try to "preserve" the "."

while read line
do
  echo line ${line}
  pdbfile=${line}\.pdb
  echo pdbfile ${pdbfile}
done < myfile

as you can see the result is the same

./testConcat
line pdb8mhtA
pdbfile pdb8mhtA.pdb


来源:https://stackoverflow.com/questions/41219148/shell-strange-string-concatenation-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!