如何在 bash 中处理每个第二个文件?

发布于 2024-10-09 13:37:38 字数 153 浏览 0 评论 0原文

我有一个包含几十个文件的目录。我想对该目录中的每个第二个文件执行一些操作。到目前为止,我只使用了 find 命令,但我用这个命令处理所有文件:

find ./dir/ -type f -exec cat {} \;

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 find command but with this I process all files:

find ./dir/ -type f -exec cat {} \;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

终遇你 2024-10-16 13:37:38
for file in `find dir -type f | awk 'NR % 2 == 0'`; do
  echo $file
done

NR 是当前行号。要获取奇数行,请使用 ... == 1

for file in `find dir -type f | awk 'NR % 2 == 0'`; do
  echo $file
done

NR is the current row number. To get odd rows, use ... == 1.

明明#如月 2024-10-16 13:37:38
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

或者

second_file=$(find -type f | head -2 | tail -1);
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);
凉墨 2024-10-16 13:37:38

如果您想在每个备用文件上运行 my_cmd,这可能会有所帮助,

 find ./dir -type f | sort -n | sed -n '1~2!p'  | sed 's/^/mycmd  /' | sh

我已从 如何使用 sed 删除所有其他行?

If you want to run my_cmd on each of the alternate file, this may help

 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?

怕倦 2024-10-16 13:37:38

每个文件我都有两次,并且需要删除每个文件。 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

将其放入名为 scriptName 的文件中,

chmod +x scriptName

通过调用运行并启动它

./scriptName

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:

#!/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

chmod +x scriptName

and start it by calling

./scriptName
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文