首页 > 解决方案 > 为什么即使我在参数中传递文本文件,我也会收到此文件错误和 cat 错误?

问题描述

该程序要求我们读取充满文本文件的目录,将这些文件中的数据解析为它们各自的属性。

然后,一旦设置了数据,就加载一个在文本中具有这些属性的通用模板。我使用 sed 命令替换特定属性,前提是学生人数大于 50。如果是这样,它会运行 sed 命令并写入文件和目录。

但是当我通过时我收到了这个错误

test3.sh ./data assign4.template 12/16/2021 ./output

错误

cat: assign4.template: No such file or directory
test3.sh: line 62: output/MAT3103.crs: No such file or directory
The current file is MAT4353.crs

现在我在想的是,对于文件或目录错误,它正在该文件夹中查找并搜索名为

但不完全确定如何解决。

至于 cat: template 错误,我不明白,因为我在终端中传递模板

至于被传递的其他参数,也被替换在 sed 命令中的日期,所有输出文件都应写入最后一个参数定义的目录。该目录可能已经存在,也可能不存在。每个文件应以课程的部门代码和编号命名,并带有扩展名.warn

这是总代码

#!/bin/bash

# checking if user has passed atleast four arguments are passed
if [ $# -ne 4 ]
then
    echo "Atleast 4 argument should be passed"
    exit 1
fi

# if output directory exits check
if [ -d output ] 
then
    # if output directory exists will get deleted
    echo "output directory already exists. So removing its contents"
    rm -f output/*
else
    # output directory does not exist, so gets created here
    echo "output directory does not exist. So creating a new directory"
    mkdir output
fi

max_students=50
template=$2
dt=$3

cd $1
    for i in *; do
    echo The current file is ${i}

    dept_code=$(awk 'NR==2
    {print $1 ; exit}' $i)
    echo $dept_code

    dept_name=$(awk 'NR==2
    {print $2 ; exit}' $i)
    echo $dept_name

    course_name=$(awk 'FNR==2' $i)
    echo $course_name

    course_sched=$(awk 'FNR==3' $i | awk '{print $1}')

    course_sched=$(awk 'FNR==3' $i | awk '{print $1}')
    echo $course_sched

    course_start=$(awk 'FNR==3' $i | awk '{print $2}')
    echo $course_start

    course_end=$(awk 'FNR==3' $i | awk '{print $3}')
    echo $course_end

    credit_hours=$(awk 'FNR==4' $i)
    echo $credit_hours

    num_students=$(awk 'FNR==5' $i)
    echo $num_students

    # checking if number of students currently enrolled > max students
    if (( $(echo "$num_students > $max_students" |bc -l) ))
    then
# output filename creation
    out_file=${i}
# using example Template and sed command to replace the variables
    cat $template | sed -e "s/\[\\[\dept_code\]\]/$dept_code/" | sed -e "s/\[\\[\dept_name\]\]/$dept_name/" | sed -e "s|\[\[course_name\]\]|$course_name|" | sed -e "s|\[\[course_start\]\]|$$

fi

done

标签: bashshellcat

解决方案


您将变量定义为

template=$2

并且由于您的第二个参数是assign4.template,这就是变量template的设置。然后你做一个

cat $template

首先,这是不必要的,因为您可以改为执行输入重定向sed,但最重要的是要求该文件存在于您的工作目录中。既然你之前做过

cd $1

这意味着该文件data/assign4.template不存在。您必须先创建此文件,然后才能使用您的脚本。


推荐阅读