Storing text and numeric variable from file to use in perl script

我是研究僧i 提交于 2019-12-14 04:10:27

问题


I am trying to prepare a bash script for use with gnu parallel. The script should take a filename, store the prefix of the file name as a describer, and store the row count (wc -l) as a numeric variable. Both if these become variables to use in a perl script. The describer is working fine.

But my storage of the number of rows, or my use of ${mm} is not generating a numeric variable that the perl script recognises. Any corrections appreciated.

#!/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:


This not an answer. I just wanted to rewrite your script in a better bash style. You know, you don't need to refer to variables with curly brackets all the time! E.g., $mm is fine enough, ${mm} is not needed in your cases. Moreover, your sed statement to strip the comment can be replaced with a bash equivalent. I added double quotes here and there so that you'll also be able to use everything with filenames that contain spaces and other funny symbols. I also removed the useless use of 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"

Regarding your main problem: the problem might be in the perl program.

Regarding your question is this a numeric variable?, the answer is: variables have no types. They all are strings. Now read on:

Some versions of wc add spaces in front of the number they output, e.g.,

$ wc -l < file
      42

(notice the spaces in front of 42). You should be able to notice if your version of wc behaves that way by running the version of the script I gave you (with the proper quotings). If you see some spaces in front of the number, that might be the cause of your problems.

If this is the case, you should replace the line

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

with

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

Hope this helps!



来源:https://stackoverflow.com/questions/17449370/storing-text-and-numeric-variable-from-file-to-use-in-perl-script

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