将bash输出写入脚本执行的每个目录

时间:2017-09-11 16:56:28

标签: bash awk

我有 N 目录,每个目录都包含以空格分隔的 .txt 文件。我想遍历每个目录并根据每个目录中的列值编写一个文件。以下是两个文件夹的案例:

folderA有一个名为 fileA.txt 的文件,folderB fileB.txt

fileA.txt

的内容
1 a
1 b
2 a
2 b 

fileB.txt

的内容
1 a
1 b
2 a
2 b 

folderAfolderB内的所需输出在这种情况下是相同的;将在包含行的两个文件夹中创建基于第一列内容的名为 1 2 的文件

1 (文件名)

1 a
1 b

2 (文件名)

2 a
2 b

分别。

到目前为止我所做的是在下面;并且无法在各自的文件夹中写入文件( 1 & 2 )。

for file in ./*.txt; do

awk -F " " '{print>$1}' $file

done

我已经尝试了几个选项来修复print>$1语句,因为这是重定向发生的地方;任何概念帮助将不胜感激。

谢谢,

1 个答案:

答案 0 :(得分:2)

在迭代以下文件之前,切换到子shell中的每个子目录:

#!/bin/bash

# configure the shell such that a glob with no matches returns zero results
shopt -s nullglob

# iterate over directories, starting a subshell for each
for dir in ./*/; do (
  # change directory within that subshell, or cause it to exit if that fails
  cd "$dir" || exit

  # ...and likewise, run awk in that subshell within the directory.
  # using "exec" is a performance optimization, consuming the subshell
  exec awk '{print>$1}' *.txt
); done

...或者,更简单一点,让find(如果你有一个-execdir扩展名)在每个目录中运行awk至少有一个{{} 1}}文件:

.txt