如何在 shell 脚本中将文件作为 stdin 传递

2024-03-14

我有一个 bash 脚本,当像这样调用时可以工作:./stats.sh -rows test_file

该程序主要计算行平均值和中位数以及列平均值和中位数。现在对于程序,我想将文件作为标准输入传递。但是当我运行这段代码时它会打印"you have 2 provide 2 arguments"。我应该进行哪些更改才能使代码将 stdin 作为文件。我的意思是说,如果我想运行脚本,我也可以通过这种方式运行它./stats.sh -rows < test_file。我想要这个功能!!

输入文件是:(由制表符分隔的列)

93  93  93  93  93  93  93  93  100
73  84  95  83  72  86  80  97  100
85  0   82  75  88  79  80  81  100
85  0   87  73  88  79  80  71  100
80  81  83  63  100 85  63  68  100
53  57  61  53  70  61  73  50  100
55  54  41  63  63  45  33  41  100
53  55  43  44  63  75  35  21  100
100 100 100 100 100 100 100 100 100

我工作的代码是这样的:

#! /bin/bash
clear
#the arguments below will check for your command line args whether you have provided corrctly or not
flag=0
if [ "$#" -eq 0 ]; then
    echo "Please provide arguments"
elif [ "$#" -lt 2 ]; then
     echo "You have to provide 2 arguments" >&2
     exit 1
elif [ "$#" -gt 2 ]; then
    echo "${#}"
    FILE= "${4}"
    if [ -f "${FILE}" ]; then
     flag=1
    else
      echo "You have provided more number of arguments" >&2
    fi
    exit 1
else
    echo "You have entered correct number of arguments"
fi
# the below code is the case code which checks whether you have -r/-rows or -c/-cols
option="${1}"
l1=0
sorted=()
case ${option} in 
   -rows| -r| -r*)
      if [ $flag -eq 1 ]; then
        FILE="${4}"
      else
        FILE="${2}"
      fi
      clear
      echo "Average  Median"
      lines=$(wc -l < "$FILE")
      while read -r line
      do
      len=0
      tot=0
      name=$line
      #array=(`echo $name | cut -d "    "  --output-delimiter=" " -f 1-`)
      IFS=' ' read -a array <<< "$name"  #if any error comes that might be with this line just check the spaces in the speech marks they should be 4 spaces as it is checking for tabs
      for element in "${array[@]}"
      do
          tot=$(expr $tot + $element)
          #let tot+=$element #you can use this as well to get the totals
          let len+=1
      done
      avg=($(printf "%.0f" $(echo "scale=2;$tot/$len" | bc)))
      readarray -t sorted < <(for a in "${array[@]}"; do echo "$a"; done | sort)
      no=`expr $len % 2`
      if [ $no -eq 0 ]; then
      mid=`expr $len / 2`
      echo "$avg   ${sorted[$mid]}"
      else
      if [ $lines -lt 2 ]; then
        mid=`expr $len / 2`
            echo "$avg   ${sorted[$mid]}"
      else
        l1=`expr $len / 2`
        mid=`expr $l1 + 1`
        echo "$avg   ${sorted[$mid]}"
      fi

      fi
      unset "array[@]"
      unset "sorted[@]"
      done < "$FILE"
      ;;

   -cols| -c| -c*)
      if [ $flag -eq 1 ]; then
        FILE="${4}"
      else
        FILE="${2}"
      fi
      #echo "cols"
      #echo "File name is $FILE"
      cols=$(head -1 "$FILE" | tr "\t" '\n' | wc -l)
      lines=$(wc -l < "$FILE")
      IFS=$'\t\n' read -d '' -r -a lins < "$FILE"
      while read line;do
      x=1
      read -a array <<< "$line" ##Split the line by spaces
      for element in "${!array[@]}"
      do
      row[${element}]=$((${row[${element}]}+${array[$element]})) ##For each column increment array variable by number in the column.
      ((x++))
      done
      done < "$FILE"
      echo "Averages: "
      for element in ${row[@]}
      do
      mean= printf "%.0f" $(echo "scale=2;$element/$lines" | bc) ##bc prints floating point numbers and then we round of using scale and .0f
      echo -n "$mean    "
      done
      printf "\n"
      echo "Medians: "
      for ((i=0;i<$cols;i++))
      do 
      carr=()
      for ((j=i;j<$lines * $cols;j=j+$cols)) 
      do
          carr+=(${lins[$j]})
      done
    IFS=$' \n' csort=($(sort <<<"${carr[*]}"))
    no=`expr $lines % 2`
    if [ $no -eq 0 ]; then
           mid=`expr $lines / 2`
           echo -n "${csort[$mid]}    "
    else
           if [ $lines -lt 2 ]; then
                  mid=`expr $lines / 2`
              echo -n "${csort[$mid]}    "
           else
              l1=`expr $lines / 2`
              mid=`expr $l1 + 1`
              echo -n "${csort[$mid]}    "
           fi
    fi
      done <<<"$lins"
      printf "\n"

      ;; 
   *)  
      echo "`basename ${0}`:usage: [-r|-rows rows] | [-c|-cols columns]" 
      exit 1 # Command to come out of the program with status 1
      ;; 
esac 
trap "echo ;exit" 1 2

您还可以在脚本中将文件重定向到 stdin:

# redirect FILE to stdin
exec 0<$FILE
# read from FILE
read VAR
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 shell 脚本中将文件作为 stdin 传递 的相关文章

随机推荐

  • 等待异步 JavaScript 函数返回

    我正在使用第三方库提供的函数 该函数接受一个回调函数作为参数 但我想等待该回调被调用后再继续 有没有标准 可接受的方法来做到这一点 我不确定这是否适合您 但您可以通过将代码分成 2 个函数来实现所需的结果 假设这是您打算做的 基本上这是你原
  • 如何在具有传递性的MySQL连接(同表)中选择不同的对?

    我面临着一个设计非常糟糕的数据库 其中有一个非规范化的表 X 该表 X 应该与另一个表 Y 具有 N M 关系 问题在于 这种关系目前是 1 N 而到目前为止 偷工减料的解决方案是在有多个注册表需要关联时复制条目 简化一下 我有这个 ID
  • 这些代码中哪一段在 Java 中速度更快?

    a for int i 100000 i gt 0 i b for int i 1 i lt 100001 i 答案就在那里这个网站 http www mydeveloperconnection com html JavaTrap htm
  • 关于 NaCL 加密库的问题

    我正在寻找实现加密系统的库 并对使用 NaCl 网络和密码学库特别感兴趣盒子功能 http nacl cr yp to box html 显然 它使用对称加密 XSalsa20 用于公私加密的 Curve25519 和用于身份验证的 Pol
  • 我们如何在 Google Glass 上启用调试模式以在 Google Glass 上测试 Android 应用程序?

    我正在开发谷歌眼镜的应用程序 但我不知道如何在谷歌眼镜中启用调试模式以及如何更改谷歌眼镜上的设置 To connect ADB to Google Glass you have to turn on debug mode on the de
  • > *:first-child 和 > :first-child 之间有功能差异吗?

    编写一段代码时 我注意到在一个地方我写了 gt first child以及后来 gt first child 这两个块看起来都很实用 但是两者之间有区别吗 即使我们考虑性能 它们也是相同的 从规格 https drafts csswg or
  • 绘图和 fill_ Between 的组合图例条目

    这类似于Matlab 结合阴影误差和实线平均值的图例 https stackoverflow com questions 17617190 matlab combine the legends of shaded error and sol
  • 运行 django 教程测试失败 - 没有名为 polls.tests 的模块

    我正在使用 django 1 6 教程 但无法运行测试 我的项目 名称 mydjango 和应用程序结构 名称是 polls 在 virtualenv 中如下所示 nja 文件是由我正在使用的 ninja ide 创建的 init py m
  • 从 Scala 中的 StructType 中提取行标记架构以解析嵌套 XML

    我正在尝试使用spark xml 库将宽嵌套的XML 文件解析为DataFrame 以下是缩写的架构定义 XSD
  • matplotlib 条形图黑色 - 如何删除条形边框

    我正在使用 pyplot bar 但我绘制了很多点 以致条形的颜色始终为黑色 这是因为条形的边框是黑色的 而且条形数量太多 以至于它们都挤在一起 所以您看到的只是边框 黑色 有没有办法删除栏边框以便我可以看到预期的颜色 Set the ed
  • 将日期字符串转换为时间戳以按亚秒精度排序

    我有一个专栏date在 pySpark 数据框中 日期格式如下 2018 02 01T13 13 12 023507 我想将该列中的日期从字符串转换为时间戳 或者我可以根据日期对其进行排序的内容 到目前为止 我已经尝试过以下方法 new d
  • 删除 Airflow Scheduler 日志

    我正在使用 Docker Apache Airflow 版本 1 9 0 2 https github com puckel docker airflow https github com puckel docker airflow 调度程
  • 使用 byte[] 读取大文件会出现错误[重复]

    这个问题在这里已经有答案了 可能的重复 在 C 中对大文件 超过 2GB 进行哈希 SHA1 https stackoverflow com questions 6094306 hash sha1 large files over 2gb
  • .NET 中的时间跨度相乘

    如何在 C 中乘以 TimeSpan 对象 假设变量duration is a TimeSpan http msdn microsoft com en us library system timespan aspx 例如我想要 durati
  • 鼠标悬停在图像上带有文本的 DIV

    好吧 首先 这真的非常类似于http dribbble com http dribbble com主页 以最简单的形式 我有一个图像 我正在尝试对其进行 CSS 处理 以便当我将鼠标悬停在图像上时 会显示一个 DIV 其中包含一些文本和部分
  • 为什么 SpeechRecognizer 突然停止工作?

    我的 Android 应用程序 Xamarin 使用语音识别 这在 Android 8 11 和 12 的智能手机上运行良好 几周以来 我的应用程序的语音识别已停止在 Android 11 上运行 测试了 2 种不同的智能手机 在Andro
  • 如何在 sympy 中求解简并方程组

    我有很多方程组 其中一些未指定 我想找到一个非零解 如果存在 或报告不存在 然而 sympy 似乎在试图找到所有解决方案时停滞不前 这是一个极端的例子 from sympy import A Matrix 0 0 0 0 0 0 0 0 0
  • 确定是否有任何双精度组合从设定总和到目标值

    我在工作中遇到一个问题 让我有点困惑 我需要验证给定的药物剂量可以由药丸剂量大小的任意组合构成 例如 dose 400 0 sizes 15 0 30 0 45 0 400 不能由这些值的任何总和创建 至少我认为这是真的 但是 如果变量更改
  • Java Swing - 半透明组件

    我最近问了一个关于半透明组件因看似未正确更新而导致奇怪的工件的问题 我收到的答案导致伪像消失 但以半透明为代价 解决方案是 对于每个半透明组件 也调用 setOpaque false 函数 这样 Swing 知道它需要重绘这些组件后面的背景
  • 如何在 shell 脚本中将文件作为 stdin 传递

    我有一个 bash 脚本 当像这样调用时可以工作 stats sh rows test file 该程序主要计算行平均值和中位数以及列平均值和中位数 现在对于程序 我想将文件作为标准输入传递 但是当我运行这段代码时它会打印 you have