[英]Why do I get many newlines after bash while loop?
我有一個簡單的 bash 腳本,它讀取 csv 文件,遍歷所有列,找到 uniq 值並將它們打印在屏幕上。 但是,在 while 循環之后會打印很多換行符。 我找不到為什么...
#!/bin/bash
INPUTFILE="loop_through_a_comma_separated_file__test_file.csv"
# Set a FIELD variable at 1 to test when to stop looping
FIELD=1
# Find how many columns are in csv and tick by 1
COUNT=`sed 's/[^,]//g' $INPUTFILE | wc -c`; let "COUNT+=1"
# Keep looping until the field is less than the count+1 (until all fields are caught in the loop)
while [ "$FIELD" -lt "$COUNT" ]; do
# Read the file and pull the current field number and print it to terminal
cat $INPUTFILE | cut -d, -f$FIELD | sort -n | uniq
# Increment the FIELD variable
((FIELD++))
done
這是文件 loop_through_a_comma_separated_file__test_file.csv 的內容:
Name,Address,Phone,Cell,Email,Nickname
1,2,3,4,5,6
7,8,9,10,11,12
1,2,3,4,5,6
如果您echo
顯COUNT
,那么您可以看到該值為25
(即number of rows * number of columns + 1
)。
COUNT=`sed 's/[^,]//g' $INPUTFILE | wc -c`; let "COUNT+=1"
上面的行計算了所有由 分隔的單詞,
即24
。 Sed 逐行處理文件。 因此,在第一行它計算 6 個單詞,然后它轉到下一行,等等直到最后。 IE。 一共4行。 由於每行有 6 個字,因此您總共得到 24 個字,即 sed 的sed
。
因此,總共將打印 25 行(即當FIELD
的值變為25
時停止)。 從 output 中的第 6 行(即FIELD
為6
時)開始,將打印空格。
很快,正如Matt Shin指出的評論中COUNT
的值是錯誤的。 如果您更改COUNT
的值,您將獲得所需的結果。
為此,您不需要sed
。
IFS=, read -a fields < "$INPUTFILE"
COUNT=${#fields[@]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.