首页 > 解决方案 > 制作文件列表并在目录中的同一文件上运行命令

问题描述

我在扩展名为 .ar 的目录中有 50 个文件。

我有一个想法,用这些文件名制作一个列表,读取每个文件,返回目录并在每个文件上运行以下 2 个命令。$i 是文件名.ar

paz -r -L -e clean $i
psrplot -pF -j CDTp  -j 'C max'  -N2,1 -D $i.ps/cps -c set=pub -c psd=0 $i $i.clean

使用 *.ar 不起作用,因为它只会覆盖第一个文件并且没有提供正确的输出。有人可以帮忙写一个 bash 脚本吗?

我使用的没有列出列表直接在目录中运行的bash脚本是

#!env 重击

for i in $@
do
        outfile=$(basename $i).txt
    echo $i
        paz -r -L -e clean $i
        psrplot -pF -j CDTp  -j 'C max'  -N2,1 -D $i.ps/cps -c set=pub -c psd=0 $i $i.clean
 done

请帮助,我已经尝试了一段时间。

标签: bashshellscripting

解决方案


您想一次处理每个文件。最安全的方法是find ... -print0使用while read .... 像这样:

#!/bin/bash
#
ardir="/data"

# Basic validation
if [[ ! -d "$ardir" ]]
then
    echo "ERROR: the directory ($ardir) does not exist."
    exit 1
fi

# Process each file
find "$ardir" -type f -name "*.ar" -print0 | while IFS= read -r -d '' arfile
do
    echo "DEBUG file=$arfile"

    paz -r -L -e clean $arfile
    psrplot -pF -j CDTp  -j 'C max'  -N2,1 -D $arfile.ps/cps -c set=pub -c psd=0 $arfile $arfile.clean
done

这种方法(还有更多!)记录在这里: http: //mywiki.wooledge.org/BashFAQ/001


推荐阅读