存储文件中的文本和数字变量以在perl脚本中使用

时间:2013-07-03 13:29:46

标签: bash variable-assignment

我正在尝试准备一个与gnu parallel一起使用的bash脚本。脚本应采用文件名,将文件名的前缀存储为描述符,并将行计数(wc -l)存储为数字变量。如果这些变为在perl脚本中使用的变量。描述者工作正常。

但我对行数的存储,或者我对$ {mm}的使用并没有生成perl脚本识别的数值变量。任何更正都会受到赞赏。

#!/bin/bash

# Get the filename and strip suffix
sample=$1
describer=$(echo ${sample} | sed 's/.sync//')
echo ${describer} # works fine

# Get the number of rows
mm=$(cat ${sample} | wc -l)
echo ${mm} # works fine but is this a numeric variable?

# run the script using the variables; 
# the ${mm} is where the perl script says its not numeric
perl script.pl --input ${describer}.sync --output ${describer}.genepop --region ${describer}:1-${mm}

1 个答案:

答案 0 :(得分:0)

这不是答案。我只是想用更好的风格重写你的脚本。你知道,你不需要一直用大括号引用变量!例如,$mm足够好,在您的情况下不需要${mm}。此外,用于删除评论的sed语句可以替换为等效语句。我在这里和那里添加了双引号,这样你也可以使用包含空格和其他有趣符号的文件名。我还删除了无用的cat

#!/bin/bash

# Get the filename and strip suffix
sample=$1
describer=${sample%.sync}
echo "$describer" # works fine

# Get the number of rows
mm=$(wc -l < "$sample")
echo "$mm" # works fine but is this a numeric variable?

# run the script using the variables; 
# the $mm is where the perl script says its not numeric
perl script.pl --input "$sample" --output "$describer.genepop" --region "$describer:1-$mm"

关于您的主要问题:问题可能出在计划中。

关于你的问题这是一个数字变量吗?,答案是:变量没有类型。它们都是字符串。现在继续阅读:

某些版本的wc会在输出的数字前添加空格,例如

$ wc -l < file
      42

(注意42前面的空格)。您应该能够通过运行我给您的脚本版本(使用正确的引用)来注意您的wc版本是否表现如此。如果您在号码前面看到一些空格,那可能是您遇到问题的原因。

如果是这种情况,您应该替换

mm=$(wc -l < "$sample")

read mm < <(wc -l < "$sample")

希望这有帮助!