【问题标题】:Bash: Extract number of filenames to move into the correct directories numberedBash:提取文件名的数量以移动到编号的正确目录中
【发布时间】:2012-12-09 02:27:28
【问题描述】:

我有一个目录中的文件列表,例如..

LDI_P1800-id1.0200.bin
LDI_P1800-id2.0200.bin
...
LDI_P1800-id17.0200.bin
LDI_P1800-id18.0200.bin
...
...
LDI_P1800-id165.0200.bin
LDI_P1800-id166.0200.bin
...

我想将它们中的每一个移动到目录中

LDI_P1800-id165.0200.bin to ../id165/.
LDI_P1800-id166.0200.bin to ../id166/.
LDI_P1800-id167.0200.bin to ../id167/.
...

等等。

我的猜测是我必须使用正则表达式从字符串中提取 id

for file in *.0200.bin ; do
    "extracting id from each file"
    mv $file ../id$id/.
done

有人可以帮我吗?谢谢!!

【问题讨论】:

  • 你试过rename方法了吗?

标签: regex string bash extract


【解决方案1】:

有几种方法可以检索该 id,其中一种是使用以下方法:

ID=$(echo $file | grep -o "id[[:digit:]]*\." | cut -b3- | tr -d '.')

它使用 grep 隔离 id[DIGITS]. 表达式,然后剪切其中的 id 部分,最后使用 tr 删除 . 字符

事实上,您可以像这样隔离整个id[DIGITS] 部分并在循环中使用它:

for file in *.0200.bin ; do
    echo "extracting id from each file"
    ID=$(echo $file | grep -o "id[[:digit:]]*\." | tr -d '.')
    mv $file ../$ID/.
done

更新:正如@dogbane 所建议的,它可以进一步简化为:

for file in *.0200.bin ; do
    echo "extracting id from each file"
    ID=$(grep -o "id[[:digit:]]*" <<< $file)
    mv $file ../$ID/.
done

【讨论】:

  • 不知道为什么您将点与grep 匹配,然后用tr 将其删除。我认为可以简化为:ID=$(grep -o "id[[:digit:]]*" &lt;&lt;&lt; $file)
【解决方案2】:

尝试以下纯 bash 解决方案:

for file in *.0200.bin
do
    id=${file#*-}      # delete everything upto the first hyphen
    id=${id%%.*}        # delete everything after the first dot
    [[ ! -d ../$id ]] && mkdir ../$id       # if the directory doesn't exist create it
    mv $file ../$id
done

也可以在sed完成,但我更喜欢第一种方法:

for file in *.0200.bin
do
    id=$(sed 's/[^-]*-\([^\.]*\).*$/\1/g' <<< $file)
    mkdir -p ../$id && mv $file ../$id
done

【讨论】:

  • 我总是忘记删除子字符串。加一。
  • mkdir 是一个 fork[ -d ../$id] 不是!所以如果不需要,不要使用-p
【解决方案3】:

您也可以在bash 中使用正则表达式(不仅仅是模式匹配)。

for f in *.0200.bin; do
    [[ $f =~ id[0-9]+ ]] && mv -- "$f" ../${BASH_REMATCH[0]}
done

BASH_REMATCH 是一个数组,其中包含最近的=~ 匹配结果。第 0 个元素包含匹配整个正则表达式的字符串。非零索引保存与正则表达式中第 *n* 个括号组匹配的结果(如果有)。

【讨论】:

    猜你喜欢
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2022-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多