bash 如何在bash中处理每个第二个文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4553751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to process every second file in bash?
提问by klew
I have a directory with a few dozens of files. I would like to do something with every second file from this directory. By now I only used findcommand but with this I process all files:
我有一个包含几十个文件的目录。我想对这个目录中的每个文件做一些事情。到目前为止,我只使用了find命令,但是我处理了所有文件:
find ./dir/ -type f -exec cat {} \;
采纳答案by ajreal
cnt=0;
for file in $(find ./dir -type f); <-- if not too many matches
do
let cnt=cnt+1;
if [ $cnt -eq 2 ];
then echo $file; <-- do something
cnt=0; <-- alternate file
fi;
done
or
或者
second_file=$(find -type f | head -2 | tail -1);
回答by plundra
for file in `find dir -type f | awk 'NR % 2 == 0'`; do
echo $file
done
NRis the current row number. To get odd rows, use ... == 1.
NR是当前行号。要获取奇数行,请使用... == 1.
回答by vrdhn
If you want to run my_cmd on each of the alternate file, this may help
如果您想在每个备用文件上运行 my_cmd,这可能会有所帮助
find ./dir -type f | sort -n | sed -n '1~2!p' | sed 's/^/mycmd /' | sh
I've copied the sed from How to remove every other line with sed?
回答by user3387542
I had every file twice, and needed to delete every second file. Find just returned me random files, therefore I added a sort. It now looks like this:
我有每个文件两次,并且需要删除每隔一个文件。Find 刚刚返回给我随机文件,因此我添加了一个排序。现在看起来像这样:
#!/bin/bash
DIRNAME="<directoryNameContainingYourFiles>"
for file in `find $DIRNAME -type f | sort | awk 'NR % 2 == 0'`; do
echo "going to modify" $file
# ls -laFh $file # show file details
# rm $file # delete file
# mv $file <newDirName> # move file to <newDirName>
done
put this in a file called scriptName, run
把它放在一个名为scriptName的文件中,运行
chmod +x scriptName
and start it by calling
并通过调用启动它
./scriptName

