将bash输出写入脚本执行的每个目录
我有N目录,每个目录都包含以空格分隔的.txt文件。我想遍历每个目录,并根据每个目录中的列值编写一个文件。以下是两个文件夹的示例:将bash输出写入脚本执行的每个目录,bash,awk,Bash,Awk,我有N目录,每个目录都包含以空格分隔的.txt文件。我想遍历每个目录,并根据每个目录中的列值编写一个文件。以下是两个文件夹的示例: folderA有一个名为fileA.txt的文件,folderB有fileB.txt fileA.txt的内容 1 a 1 b 2 a 2 b 1 a 1 b 2 a 2 b fileB.txt的内容 1 a 1 b 2 a 2 b 1 a 1 b 2 a 2 b 在这种情况下,folderA和folderB内的期望输出相同;也就是说,根据第一列的内
folderA
有一个名为fileA.txt的文件,folderB
有fileB.txt
fileA.txt的内容
1 a
1 b
2 a
2 b
1 a
1 b
2 a
2 b
fileB.txt的内容
1 a
1 b
2 a
2 b
1 a
1 b
2 a
2 b
在这种情况下,folderA
和folderB
内的期望输出相同;也就是说,根据第一列的内容命名为1和2的文件将在包含行的两个文件夹中创建
1(文件名)
2(文件名)
分别
到目前为止,我所做的如下;无法在各自的文件夹中写入文件(1&2)
for file in ./*.txt; do
awk -F " " '{print>$1}' $file
done
我尝试了几个选项来修复print>$1
语句,因为这就是重定向发生的地方;任何概念帮助都将不胜感激
谢谢,在迭代以下文件之前,请先更改子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
…或者,更简单的是,让
查找
(如果您有一个带有-execdir
扩展名)在每个目录中运行awk
,其中至少有一个.txt
文件:
find . -name '*.txt' -execdir awk '{print>$1}' {} +
在迭代子shell中的文件之前,请更改为子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
…或者,更简单的是,让
查找
(如果您有一个带有-execdir
扩展名)在每个目录中运行awk
,其中至少有一个.txt
文件:
find . -name '*.txt' -execdir awk '{print>$1}' {} +
你使用
awk
有什么原因吗?不是真的@charlesduffyy你也可以运行循环,虽然awk
实际上是一个不错的选择。你使用awk
有什么原因吗?不是真的@charlesduffyy你也可以运行循环,虽然awk
实际上是一个不错的选择。就像一个魔咒。。。非常感谢你。工作起来很有魅力。。。非常感谢你。