我有一堆使用约定前缀后缀命名的目录。前缀是数字,后缀是任意长度的字母数字。
mkdir 123.abcdef
前缀总是唯一的,但我并不总是知道脚本运行时的后缀是什么。
在我的脚本中,如何通过只知道前缀来让bash写入给定的目录?以下方法不起作用,但我尝试了:
bash

最佳答案

Glob要在globs上循环的目录部分:

shopt -s nullglob

for dir in 123*/; do
    echo "itworks" > "${dir}results.text"
done

您还可以强制检查是否存在唯一的目录匹配:
shopt -s nullglob

dirs=( 123*/ )
if (( ${#dirs[@]} == 0 )); then
    echo >&2 "No dirs found!"
    exit 1
elif (( ${#dirs[@]} > 1 )); then
    echo >&2 "More than one dir found!"
    exit 1
fi

# Here you're good
echo "itworks" > "${dirs[0]}results.txt"

关于bash - bash在目录中创建文件,仅部分目录名是已知的,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37972625/

10-13 07:42
查看更多