假设我在文件夹中有:
我的文件夹
以下文件:
File1.txt File2.txt File3.txt File9.txt Bob.txt
我想应用以下算法,但我不知道如何在 Bash 中执行(实际上循环 For 是我无法做到的):
For (each file of MyFolder directory)
add "<end>" at the end of the current text file
EndFor
bash 中的正确语法是什么?
预先感谢您的帮助。
这可以使它:
for file in /your/dir/*
do
echo "<end>" >> "$file"
done
如果你里面有一些目录,你可能会得到错误bash: XX: Is a directory。为避免看到它们,您可以2>/dev/null在命令末尾添加echo:
echo "<end>" >> "$file" 2>/dev/null
或者更好(感谢 Barmar),检查它们是否是文件:
[ -f "$file" ] && echo "<end>" >> "$file"
这是执行 if 条件的一种简短方法:
if [ -f "$file" ]; then
echo "<end>" >> "$file"
fi
一种方法是这样的
#!/bin/bash
folder="myfolder"
for i in `find $folder/ -type f`
do
echo $i
echo "<end>" >> "$i"
done
这是find一个班轮:
find /your/dir/ -maxdepth 1 -type f -exec sh -c 'echo "<end>" >> {}' \;
不将文件包含在-maxdepth 1子文件夹中的
地方-type f是仅用于查找文件并-exec为每个找到的项目触发 echo 命令。