Bash for循环从文件中拉出文本

问题描述 投票:0回答:2

我在编写Bash for循环脚本时遇到问题,该脚本可以提取父目录下许多子目录通用的特定文件的内容。

目录结构:

/Parent/child/grand_child/great_grand_child/file

其中有许多孩子,孙子和孙子文件夹。

我想要我的脚本(伪代码):

对于每个grand_child文件夹,在每个子文件夹中:

  1. 只搜索一个great_grand_child文件夹
  2. 找到名为0001.txt的文件
  3. 将0001.txt第10行中的文本打印到输出文件
  4. 在输出文件的下一列中,打印提取文本的文件的完整目录路径。

我的脚本到目前为止:

for i in /Parent/**; do
if [ -d "$i" ]; then
echo "$i"
fi
done

我可以帮助设计这个脚本吗?到目前为止,这给了我每个grand_child文件夹的路径,但我不知道如何只隔离一个great_grand_child文件夹,然后在great_grand_child文件夹中的0001.txt文件的第10行中询问文本。

bash for-loop
2个回答
1
投票
# 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

1
投票

鉴于名称是理智的(没有空格或其他尴尬的字符),那么我可能会选择:

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中的输出。

© www.soinside.com 2019 - 2024. All rights reserved.