簡體   English   中英

如何在Linux bash中將相鄰行放在.txt文件中的同一行上?

[英]How do I put adjacent lines in a .txt file on the same line in linux bash?

所以我是bash linux的新手,我正在嘗試修復.txt文件。

我有一個.txt文件,看起來像這樣:

blueberry, "yummy", 12345, "I love fruit and eating apples"
blueberry, "tasty", 4455, "fruit is good for you"
blueberry, "yum", 109833, "I go crazy for fruit"
blueberry, "wooohh", 1347672, "I love fruit and 
eating apples"
blueberry, "yummy yummy", 1023433, "I love fruit more than my dog"
blueberry, "yummy", 12345, "I love fruit and eating apples"
blueberry, "something good to eat", 42, "fruit is the 
greatest thing EVER"
blueberry, "tasty", 4455, "fruit is good for you"
blueberry, "yum", 109833, "I go crazy for fruit"

我想創建一個新的.txt文件,如下所示:

blueberry, "yummy", 12345, "I love fruit and eating apples"
blueberry, "tasty", 4455, "fruit is good for you"
blueberry, "yum", 109833, "I go crazy for fruit"
blueberry, "wooohh", 1347672, "I love fruit and eating apples"
blueberry, "yummy yummy", 1023433, "I love fruit more than my dog"
blueberry, "yummy", 12345, "I love fruit and eating apples"
blueberry, "something good to eat", 42, "fruit is the greatest thing EVER"
blueberry, "tasty", 4455, "fruit is good for you"
blueberry, "yum", 109833, "I go crazy for fruit"

(因此,將兩行中的隨機句子放回一起)

到目前為止,我已經嘗試過使用echo這樣的方式:

while read p; do                      #for every line in the .txt file
  if[[ $p == "blueberry"* ]]          #if the line starts with 'blueberry' 
       echo -n "$p" >> newfruit.txt   #add the line to newfruit.txt without a new line
  else
       echo " $p" >> newfruit.txt     #add to the current line
  fi
done <fruit.txt

但它只是返回完全相同的.txt文件,我也嘗試使用printf和echo -e獲得相同的結果

任何建議或技巧將不勝感激! 謝謝!

您有幾個語法錯誤: if[[需要一個空格, if需要一個then。 除此之外,您的邏輯有點不正確。 應該這樣做:

while read p; do
  if [[ $p == "blueberry"* ]]; then
    if [[ -n "$notfirst" ]]; then      # in all blueberry lines but the first,
      echo >> newfruit.txt             # make sure the previous line is terminated
    fi
    echo -n "$p" >> newfruit.txt       # then wait for possible continuation
  else
    echo -n " $p" >> newfruit.txt      # there's the continuation!
  fi
  notfirst=1                           # don't add newline before the first line
done < fruit.txt

if [[ -n "$notfirst" ]]; then          # do add the newline after the last line
  echo >> newfruit.txt
fi
awk '{printf $0}/"$/{printf "\n"}' fruit.txt

打印每行而沒有換行符。 如果行以“結尾”,則打印換行符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM