Bash字符串替换%用法问题:提取S2前缀文件的唯一名称
Got it, let's break down what's going wrong and fix it step by step.
First, your original code had a small variable name mix-up (S2_FASTQ instead of FASTQ), but even fixing that, the pattern you used won't handle the S2_ prefix correctly. Here's how to adjust your loop to extract the exact sample name you need and rename the files to use an S3_ prefix:
for BED_FILE in S2_*.bed; do # Step 1: Remove the leading S2_ prefix TEMP=${BED_FILE#S2_} # Step 2: Remove the trailing .bed suffix SAMPLE=${TEMP%.bed} # Step 3: Rename the file to use S3_ prefix mv "$BED_FILE" "S3_${SAMPLE}.bed" done
How this works:
${BED_FILE#S2_}: This uses parameter expansion to strip the shortest matching prefix (S2_) from the filename. ForS2_7-CHX-2-13_Chr27.bed, this gives you7-CHX-2-13_Chr27.bed.${TEMP%.bed}: Similarly, this strips the shortest matching suffix (.bed) from the temporary string, leaving you with your desired sample name:7-CHX-2-13_Chr27.- The
mvcommand then renames the originalS2_*.bedfile toS3_${SAMPLE}.bed, which would turnS2_7-CHX-2-13_Chr27.bedintoS3_7-CHX-2-13_Chr27.bed.
If you want to condense it into a single line for the sample name extraction (for brevity), you can nest the expansions:
SAMPLE=${${BED_FILE%.bed}#S2_}
Just note that some older shell versions might not support nested parameter expansion, so the two-step approach is more universally compatible.
Also, remember to always quote your variables (like "$BED_FILE" and "S3_${SAMPLE}.bed") to handle any filenames that might contain spaces or special characters down the line.
内容的提问来源于stack exchange,提问作者Sarah

