【问题标题】:How to read from two files in the same time shell如何在同一时间shell中读取两个文件
【发布时间】:2013-03-26 16:56:43
【问题描述】:

我有两个文件,

A

john 1 2 3 4 5 6 7
Ely 10 9 9 9 9 9 9
Maria 3 5 7 9 2 1 4
Rox 10 10 10 10 10 10 10

B 
john 7.5
Ely 4.5
Maria 3,7
Rox 8.5

我想要做的是创建另一个文件,其中只有在文件 A 中他们的平均值大于或等于 8.5 并且在 B 中他们的标记也大于或等于 8.5 的人,所以在我的示例中,C 文件将包含只有 Rox,因为只有她符合条件。

我有这个

#shell program
echo "Fiserul are numele $1"
filename=$1
filename2=$2
echo "">temp.txt
touch results
compara="8.5"
cat $filename | while read -r line
do
    nota=0
    media=0
    echo " $line"
    rem=$( echo "$line"| cut -f 2- -d ' ')
    for word in $rem 
    do
        echo "$word"
        nota=$(($nota+$word))
        echo "Nota=$nota"
    done
    media=$(($nota / 7))
    if [ "$(echo $media '>=' $compara | bc -l)" -eq 1 ];
    then 
        nume=$( echo "$line"| cut -f 1 -d ' ')
        echo "$nume $media" >> temp.txt
    fi
    echo "Media : $media"
done
cat $filename2 | while read -r line
do

所以我在 temp.txt 文件中有满足文件 A 标准的人,但我的问题是如何将他们与来自 filename2 的人进行比较并从中创建“结果”? 我尝试了两个while循环,但出现错误,有人可以帮忙吗? 谢谢!

【问题讨论】:

  • 这在 awk 中会容易得多,但我没有时间为你勾勒出来。祝你好运。
  • 嘿,谢谢你的提示!
  • @shellter - 有史以来最差答案奖!恭喜!问:“我怎么骑自行车去芝加哥?” A:“好吧,我开车送你去那里会容易得多,因为我有一辆非常好的车,而且我也很聪明,但很抱歉我没有时间。祝你好运!”
  • @user3133172,您会注意到该评论是作为 comment 提出的,而不是答案。此外,对于 OP 的真正问题,awk is 是更好的工具——支持正确的浮点数学意味着所有使用 bc 的黑客都是不必要的。同样,所有调用 cut 和类似工具的子进程(尽管它们在 bash 中也不是必需的,但这是 OP 不知道可用的本机字符串操作工具并诉诸进程外工具的证据)。

标签: file shell unix printing


【解决方案1】:

如果您真的想同时读取两个文件(这似乎不是您的实际问题——join 确实是您正在做的事情的正确工具) ,您可以在不同的 FD 上打开它们:

while IFS= read -r -u 4 line1 && IFS= read -r -u 5 line2; do
  echo "Line from first file: $line1"
  echo "Line from second file: $line2"
done 4<file1 5<file2

【讨论】:

    【解决方案2】:

    使用join命令将A和B合并到一个文件C中:

    $ join A.txt B.txt
    john 1 2 3 4 5 6 7 7.5
    Ely 10 9 9 9 9 9 9 4.5
    Maria 3 5 7 9 2 1 4 3,7
    Rox 10 10 10 10 10 10 10 8.5
    

    修改当前脚本以处理此表单中的数据应该很简单。

    【讨论】:

      猜你喜欢
      • 2016-03-09
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      相关资源
      最近更新 更多