拆分文件名并在下划线的第一个和最后一次出现之间获取元素



我试图将许多文件夹在for循环中拆分许多文件夹名称,并在文件名的第一个和最后一个下划线之间提取元素。文件名看起来像ENCR000AMA_HEPG2_CTCF或ENGSR000ALA_ENDOLIAL_CELL_CELL_OF_BUMILICAL_VEIN_VEIN_CTCF。

我的问题是文件夹名称在下划线的总数中相互不同,因此我不能使用以下内容:

IN=$d
folderIN=(${IN//_/ })
tf_name=${folderIN[-1]%/*} #get last element which is the TF name
cell_line=${folderIN[-2]%/*}; #get second last element which is the cell line
dataset_name=${folderIN[0]%/*}; #get first element which is the dataset name

cell_line可以是一个或多个单词,被下划线隔开,但在第一个和最后一个下划线之间。

有帮助吗?

只需在两个步骤bash参数扩展中仅在中进行此操作,因为bash不支持zsh或其他Shells不同。

"${string%_*}"在最后一次出现" _'"和 "${tempString#*_}"之后剥离所有内容,以剥离从开始到首次出现'_''

的所有内容
string="ENCSR000ALA_endothelial_cell_of_umbilical_vein_CTCF"
tempString="${string%_*}"
printf "%sn" "${tempString#*_}"
endothelial_cell_of_umbilical_vein

另一个例子

string="ENCSR000AMA_HepG2_CTCF"
tempString="${string%_*}"
printf "%sn" "${tempString#*_}"
HepG2

您可以修改此逻辑以应用于文件夹中的每个文件名。

可以使用正则。

extract_words() {
    [[ "$1" =~ ^([^_]+)_(.*)_([^_]+)$ ]] && echo "${BASH_REMATCH[2]}"
}
while read -r from_line
do
    extracted=$(extract_words "$from_line")
    echo "$from_line" "[$extracted]"
done < list_of_filenames.txt

编辑:我将"提取"移至一个单独的bash功能中,以重复使用,并轻松修改更复杂的情况,例如:

extract_words() {
        perl -lnE 'say $2 if /^([^_]+)_(.*)_([^_]+)$/' <<< "$1"
}

相关内容