【问题标题】:making file list and running commands on same file in directory制作文件列表并在目录中的同一文件上运行命令
【发布时间】:2021-10-15 03:57:53
【问题描述】:

我在一个扩展名为 .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 bash

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

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

【问题讨论】:

  • "$@" "$i" 应该被引用
  • 这里有一些奇怪的东西:你分配了outfile,但你没有使用它。 psrplot我不熟悉,但是哪个参数指定它的输出文件?

标签: bash shell scripting


【解决方案1】:

您希望一次处理一个文件。最安全的方法是使用find ... -print0while 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-10
    • 2013-08-04
    • 2023-03-02
    • 2014-05-21
    • 1970-01-01
    • 2012-10-16
    • 2019-08-13
    • 2013-12-03
    相关资源
    最近更新 更多