我在编写Bash for循环脚本时遇到问题,该脚本可以提取父目录下许多子目录通用的特定文件的内容。
目录结构:
/Parent/child/grand_child/great_grand_child/file
其中有许多孩子,孙子和孙子文件夹。
我想要我的脚本(伪代码):
对于每个grand_child文件夹,在每个子文件夹中:
我的脚本到目前为止:
for i in /Parent/**; do
if [ -d "$i" ]; then
echo "$i"
fi
done
我可以帮助设计这个脚本吗?到目前为止,这给了我每个grand_child文件夹的路径,但我不知道如何只隔离一个great_grand_child文件夹,然后在great_grand_child文件夹中的0001.txt文件的第10行中询问文本。
# For every grandchild directory like Parent/Child/Grandchild
for grandchild in Parent/*/*
do
# Look for a file like $grandchild/Greatgrandchild/0001.txt
for file in "$grandchild/"*/0001.txt
do
# If there is no such file, just skip this Grandchild directory.
if [ ! -f "$file" ]
then
echo "Skipping $grandchild, no 0001.txt files" >&2
continue
fi
# Otherwise print the 10th line and the file that it came from.
awk 'FNR == 10 { print $0, FILENAME }' "$file"
# Don't look at any more 0001.txt files in this Grandchild directory,
# we only care about one of them.
break
done
done
鉴于名称是理智的(没有空格或其他尴尬的字符),那么我可能会选择:
find /Parent -name '0001.txt' |
sort -t / -k1,1 -k2,2 -k3,3 -u |
xargs awk 'FNR == 10 { print $0, FILENAME }' > output.file
在0001.txt
下找到名为/Parent
的文件。对列表进行排序,以便每个/Parent/Child/Grandchild
只有一个条目。根据需要经常运行awk
,打印每个文件的第10行以及文件名。捕获output.file
中的输出。