【问题标题】:shell: strange string concatenation behavior [duplicate]shell:奇怪的字符串连接行为[重复]
【发布时间】:2020-04-07 23:50:21
【问题描述】:

我这样写一个scipt:

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

结果是:

line pdb8mhtA
.pdbfile pdb8mhtA

应该是这样的

line pdb8mhtA
pdbfile pdb8mhtA.pdb

这有什么问题?为什么字符串连接不起作用?为什么行首出现奇怪的点?
我替换为pdbfile=${line}'.pdb'。这不会改变结果。

【问题讨论】:

  • 输入中会不会有回车(\r)字符?
  • 您可以尝试以下操作:od -xc myfile 并将结果粘贴到此处吗?怀疑是文件中有一个奇怪的字符正在搞砸。
  • 我用简单的复制/粘贴测试了你的脚本,它工作正常。我尝试在输入文件的第一行之后添加一个\r 字符(如@Biffen 所建议的那样),我得到了您向我们展示的输出。为了从您的输入数据中去除 Windows 风格的回车,我建议运行以下脚本:sed -i 's/^M//g' myfile

标签: bash shell string-concatenation


【解决方案1】:

“字符串到行首”是$line 中的回车的症状,您可以通过tr 管道将其删除到您的文件中:

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

【讨论】:

  • ...顺便说一句,回复:编辑,请参阅 BashFAQ #1 描述为什么 IFS= read -r lineread line 更正确,BashPitfalls #14 描述为什么需要引用 echo 的参数,以及porkmail.org/era/unix/award.html 讨论指责那些不必要地使用cat 的人的悠久历史(对tr 来说并不重要,但如果你养成使用它的习惯,你可能会将它用于tail 或@987654333 @,或另一个程序,它表示 O(1) 和 O(n) 操作之间的差异)。
【解决方案2】:

我已经尝试过你的脚本,它对我来说效果很好:

./testConcat
line pdb8mhtA
pdbfile pdb8mhtA.pdb

顺便说一句,您可以尝试“保留”“。”

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

如你所见,结果是一样的

./testConcat
line pdb8mhtA
pdbfile pdb8mhtA.pdb

【讨论】:

  • 谢谢:) 我试图逃避这个点,但没有帮助。
猜你喜欢
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 1970-01-01
  • 2016-12-26
  • 1970-01-01
相关资源
最近更新 更多