首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在linux bash中,如何将.txt文件中的相邻行放在同一行上?

在linux bash中,如何将.txt文件中的相邻行放在同一行上?
EN

Stack Overflow用户
提问于 2015-08-25 08:48:50
回答 2查看 78关注 0票数 0

所以我是bash linux的新手,我正在尝试修复一个.txt文件。

我有一个类似如下的.txt文件:

代码语言:javascript
复制
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文件,如下所示:

代码语言:javascript
复制
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,如下所示:

代码语言:javascript
复制
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

但它只返回与我尝试使用printf和echo -e时完全相同的.txt文件,并返回相同的结果

如果您有任何建议或建议,我们将不胜感激!谢谢!

EN

回答 2

Stack Overflow用户

发布于 2015-08-25 08:58:12

有几个语法错误:if[[需要一个空格,if需要一个then。除此之外,你的逻辑有点不正确。这应该可以做到:

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2015-08-25 13:52:18

代码语言:javascript
复制
awk '{printf $0}/"$/{printf "\n"}' fruit.txt

打印每一行,不带换行符。如果行以“结尾,则打印换行符

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32193902

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档