bash 在目录中创建文件,只知道部分目录名
bash create file in directory, only part of directory name is known
我有一堆目录使用约定 prefix.suffix 命名。 prefix 是数字,suffix 是任意长度的字母数字。
mkdir 123.abcdef
prefix 始终是唯一的,但我并不总是知道 bash
脚本运行时的 suffix 是什么。
在我的脚本中,如何通过仅知道 前缀 来让 bash
写入给定目录?
以下内容不起作用,但我试过了:
echo "itworks" > 123*/results.text
glob 目录部分以在 glob 上循环:
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"
您可以使用 'ls -d'
强制计算带有通配符的目录名称
echo "itworks" > $(ls -d 123*)/results.txt
prefix='yourprefix' && find . -maxdepth 1 -type d -name "$prefix*" \
-exec echo "Hello" {}/results.txt \;
应该做。
我有一堆目录使用约定 prefix.suffix 命名。 prefix 是数字,suffix 是任意长度的字母数字。
mkdir 123.abcdef
prefix 始终是唯一的,但我并不总是知道 bash
脚本运行时的 suffix 是什么。
在我的脚本中,如何通过仅知道 前缀 来让 bash
写入给定目录?
以下内容不起作用,但我试过了:
echo "itworks" > 123*/results.text
glob 目录部分以在 glob 上循环:
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"
您可以使用 'ls -d'
强制计算带有通配符的目录名称echo "itworks" > $(ls -d 123*)/results.txt
prefix='yourprefix' && find . -maxdepth 1 -type d -name "$prefix*" \
-exec echo "Hello" {}/results.txt \;
应该做。