0

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.

dudu
  • 801
  • 1
  • 10
  • 32
  • 2
    Could there be carriage return (`\r`) characters in the input? – Biffen Dec 19 '16 at 09:19
  • Can you try the following: `od -xc myfile` and paste the result here? The suspicion is that there is a strange character in the file which is messing things up. – cdarke Dec 19 '16 at 09:31
  • I tested your script with simple copy/pasting, and it works fine. I tried adding a `\r` character after the 1st line of my input file (as suggested by @Biffen) and I get the output you've shown us. In order to strip Windows-style carriage return from your input data, I suggest running the following script : `sed -i 's/^M//g' myfile` – Aserre Dec 19 '16 at 09:35

2 Answers2

3

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)
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
SLePort
  • 15,211
  • 3
  • 34
  • 44
  • ...btw, re: edits, see [BashFAQ #1](http://mywiki.wooledge.org/BashFAQ/001) describing why `IFS= read -r line` is more correct than `read line`, [BashPitfalls #14](http://mywiki.wooledge.org/BashPitfalls#echo_.24foo) describing why arguments to `echo` need to be quoted, and http://porkmail.org/era/unix/award.html discussing the long history of chiding folks who use `cat` unnecessarily (doesn't really matter for `tr`, but if you get in the habit for using it, you might use it for `tail`, or `wc -c`, or another program where it means the difference between O(1) and O(n) operation). – Charles Duffy Apr 07 '20 at 15:52
-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
ClaudioM
  • 1,418
  • 2
  • 16
  • 42