Freesurfer成像分析脚本报错:expr substr语法错误缺失参数
问题解决:expr语法错误及脚本优化
错误原因
你遇到的 expr: syntax error: missing argument after '3' 错误,源于使用外部工具expr进行字符串截取时的兼容性问题。expr对输入字符串中的特殊字符(如连字符、空格)敏感,且依赖严格的参数格式,容易触发语法错误。
核心修复
将依赖expr的字符串截取代码替换为Bash内置的字符串操作,既避免外部工具的兼容性问题,又提升效率:
原代码:
idx=`expr substr $filename 1 3`
替换为:
idx="${filename:0:3}"
注:Bash的${var:start:length}语法是0索引,这里0:3表示从第1个字符开始截取3个字符,和原expr substr $filename 1 3的效果完全一致。
其他脚本优化建议
为提升脚本稳定性和可读性,还可以做以下调整:
替换过时的命令替换语法:用
$()替代反引号(`),后者在嵌套使用时容易出错:input_file=$(sed "${SLURM_ARRAY_TASK_ID}q;d" nii_filelist)完善find命令:添加
-type f确保只查找文件,用.替代~+更清晰:find . -type f -name "*T1w_*.nii" > "$SUBJECTS_DIR/nii_filelist"增加文件存在检查:避免因文件列表为空或索引超出范围导致后续命令失败:
if [ ! -f "$input_file" ]; then echo "Error: Input file $input_file not found" exit 1 fi变量引用加引号:所有变量引用都用双引号包裹,防止文件名含空格或特殊字符时出错:
filename=$(basename -- "$input_file")
修复后的完整脚本
#!/bin/bash #SBATCH -c 8 # Number of Cores per Task #SBATCH --mem=16GB # Requested Memory;increased memory. #SBATCH -p cpu # Partition; cpu partition is for 24 hours; cpu-long is 30 days #SBATCH -t 12:00:00 # Job time limit #SBATCH -o slurm-%A_%a.out #%a= job ID #SBATCH -e slurm-%A_%a.err #any error output per participant #SBATCH --array=1-39%39 #SBATCH --nodes=1 #SBATCH --ntasks-per-node=1 #SBATCH --cpus-per-task=8 #SBATCH --time=12:00:00 #SBATCH --mail-type=ALL #SBATCH --mail-user=iorlovsky@umass.edu export FREESURFER_HOME=/home/iorlovsky_umass_edu/freesurfer source "$FREESURFER_HOME/SetUpFreeSurfer.sh" export SUBJECTS_DIR=/work/pi_rspencer_umass_edu/T1W_Scans cd "$SUBJECTS_DIR" || exit 1 # 生成文件列表,仅查找文件 find . -type f -name "*T1w_*.nii" > "$SUBJECTS_DIR/nii_filelist" # 获取当前任务对应的输入文件 input_file=$(sed "${SLURM_ARRAY_TASK_ID}q;d" nii_filelist) # 检查文件是否存在 if [ ! -f "$input_file" ]; then echo "Error: Input file $input_file not found" exit 1 fi # 提取文件名和前缀 filename=$(basename -- "$input_file") idx="${filename:0:3}" # 运行FreeSurfer重建 recon-all -s "EMO${idx}" -i "$input_file" -all -openmp 4
内容的提问来源于stack exchange,提问作者Irina Orlovsky
相关产品推荐
相关产品推荐

