【问题标题】:manipulating a text file in bash在 bash 中操作文本文件
【发布时间】:2014-03-15 14:36:31
【问题描述】:

我需要有关 bash 中的 ext 文件操作的帮助 我有三个文件 call.txt、subscribers.txt、towns.txt the link for the files 我需要帮助编写一个方法,该方法将从键盘读取 caller_town,然后搜索已拨打 caller_town 的订阅者的姓名。

它应该以这种格式打印:

订阅者名称 1

  • 拨打 1
  • 呼叫 2
  • 呼叫 3

订阅者名称 2

  • 拨打 1
  • 呼叫 2
  • 呼叫 3

这是我的代码:

!/bin/bash
exec 401<> calls.txt 
while read line <&401      # read a line at a time from calls.txt
do                         # if end of file reached, while will yield false the$
{

full_line=$line;       # because $line is going to change, store it somewhe$


    date=${line%%|*}; # cut off the rest of $line but keep date 
    line=${line#*|};       


    time=${line%%|*}; # cut off the rest of $line but keep time
    line=${line#*|};       

    duration=${line%%|*};  # cut off the rest of $line but keep box
    line=${line#*|};       



    callee=${line%%|*};   # cut off the rest of $line but keep callee
    line=${line#*|};      



    caller=${line%%|*};   # cut off the rest of $line but keep caller
    line=${line#*|};      


    calleeLoc=${line%%|*};   # cut off the rest of $line but keep callee location
    line=${line#*|};


    callerLoc=${line%%|*};   # cut off the rest of $line but keep caller location
    line=${line#*|};

caller_details=$(grep -m 1 "$caller_id" subscribers.txt)
caller_name=$(echo $caller_details | cut -d\| -f2)
caller_town=$(grep -m1 "$(echo $caller_details | cut -d\| -f5)" towns.txt | cut -d\| -f2)

我需要此方法的帮助,因为它为每个订阅者打印 1 个呼叫,而不是打印多个呼叫

    if [ $caller = $callerID ]
     then  

       echo $caller_name;
       echo $date"|"$time"|"$duration"|"$callee"|"$caller"|"$calleeLoc"|"$callerLoc;
   fi  


}
done


exec 401>&-

【问题讨论】:

  • 学习使用sedawk,也许还有ed
  • 缺少done。请显示输入文件。

标签: linux bash awk delimiter do-while


【解决方案1】:

我想这将大致完成这项工作。尝试与您自己的代码相结合,而不仅仅是复制粘贴到您的作业解决方案中。

#!/bin/bash

echo -n "enter town: "
read caller_town

town_id=$(grep "|$caller_town|" towns.txt | awk -F '|' '{ print $1; }')

while read line; do
  caller_id=$(echo "$line" | awk -F '|' '{ print $1; }')
  egrep "\|$caller_id\|[0-9]+\|$town_id$" calls.txt > /dev/null
  if [ $? -eq 0 ]; then
    echo "$line" | awk -F '|' '{ print $2; }'
    egrep "\|$caller_id\|[0-9]+\|$town_id$" calls.txt
    echo
  fi
done < subscribers.txt

【讨论】:

  • @tonto 请确保通过单击答案旁边的勾号标记您的问题已解决来接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多