读取行时-限制行数

时间:2018-09-06 13:38:37

标签: bash while-loop

我试图限制在while读取行循环中找到的行数。例如:

文件:order.csv

com.microsoft.graph.http.GraphFatalServiceException: Unexpected exception returned from the service.GET https://graph.microsoft.com/v1.0/users/me/messages?$filter=IsDraft+eq+false+and+ReceivedDateTime+ge+2017-09-06T12%3a02%3a26.608Z&$orderby=ReceivedDateTime+desc&$expand=SingleValueExtendedProperties(%24filter%3did+eq+%27String+0x7D%27)%2cattachments&$select=conversationId%2cchangeKey%2csentDateTime%2creceivedDateTime%2cisRead%2chasAttachments%2cinternetMessageHeaders%2csender%2cfrom%2ctoRecipients%2cccRecipients%2cbccRecipients%2csubject%2cinternetMessageId%2cbody%2cattachments&$top=100&$skip=6426
SdkVersion : graph-java-v0.2.0
Authorization : Bearer eyJ0eXAiOiJKV1QiLCJub25jZSI[...]
client-request-id : 38246tl5hwutoukh6qb

504 : Gateway Timeout

我正在做以下事情。

 123456,ORDER1,NEW
 123456,ORDER-2,NEW
 123456,ORDER-3,SHIPPED

哪个输出:

 cat order.csv | while read line;
 do
  order=$(echo $line | cut -d "," -f 1)
  status=$(echo $line | cut -d "," -f 3)
  echo "$order:$status"
 done

如何限制行数。在这种情况下,有三个。如何将它们限制为仅2个,以便仅显示前两个?

所需的输出:

  123456:NEW
  123456:NEW
  123456:SHIPPED

1 个答案:

答案 0 :(得分:0)

有一些方法可以满足您的要求:

方法1

使用head显示文件的前几行。

head -n 2 order.csv | while read line;
do
    order=$(echo $line | cut -d "," -f 1)
    status=$(echo $line | cut -d "," -f 3)
    echo "$order:$status"
done

方法2

使用for循环。

for i in {1..2}
do
    read line
    order=$(echo $line | cut -d "," -f 1)
    status=$(echo $line | cut -d "," -f 3)
    echo "$order:$status"
done < order.csv

方法3

使用awk

awk -F, 'NR <= 2 { print $1":"$3 }' order.csv