【问题标题】:how to replace 2 new lines by one in the file如何在文件中用一个替换2个新行
【发布时间】:2014-03-14 09:43:13
【问题描述】:

我有以下文本文件

config 'toto'
        option 
        option 

config 'titi'
        list 
        list 

config 'tutu'
        list 
        list 

当我使用cat 显示文件时,我只想将每 2 个新行替换为一个。

我尝试了以下命令,但它们不起作用

cat file | sed -e "s@$'\n'$'\n'@$'\n'@g"
cat file | sed -e "s@\n\n@\n@g"

预期的输出是这样的:

config 'toto'
        option 
        option 
config 'titi'
        list 
        list 
config 'tutu'
        list 
        list 

【问题讨论】:

  • 你能添加你期望输出的样子吗
  • @mikea : 问题更新与预期输出
  • grepping 空行对你来说就足够了吗?
  • grep -v '^$' filename

标签: bash shell sed awk ash


【解决方案1】:

sed:

sed '/^$/d' file

(或)

sed '/^[ ]*$/d' file

tr:

tr -s '\n' < file

【讨论】:

    【解决方案2】:

    使用sed

    $ sed '/^$/d' foo.txt
    config 'toto'
            option
            option
    config 'titi'
            list
            list
    config 'tutu'
            list
            list
    

    如果你的空行包含空格,你可以使用

    $ sed '/^\s*$/d' foo.txt
    

    $ sed '/^[[:space:]]*$/d' foo.txt
    

    也将它们过滤掉。

    使用awk

    $ awk '!/^[[:space:]]*$/' foo.txt
    

    使用grep

    $ grep -v '^[[:space:]]*$' foo.txt
    

    【讨论】:

      【解决方案3】:

      小小awk:

      awk 'NF' file
      

      $ cat file
      config 'toto'
              option 
              option 
      
      config 'titi'
              list 
              list 
      
      config 'tutu'
              list 
              list 
      

      $ awk 'NF' file
      config 'toto'
              option 
              option 
      config 'titi'
              list 
              list 
      config 'tutu'
              list 
              list 
      

      【讨论】:

        【解决方案4】:
        egrep -v '^ *$' YourFile
        

        应该比sed快

        【讨论】:

          【解决方案5】:

          您可以使用 Bash while read 循环。

          while IFS='' read line; do
              if [ -z "$line" ]; then
                  continue
              else
                  echo "$line"
              fi
          done < file
          

          这里,循环将打印每一行非空字符串。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-07-28
            • 1970-01-01
            • 2018-03-20
            • 2012-09-04
            • 1970-01-01
            相关资源
            最近更新 更多