2

I have the following text file

config 'toto'
        option 
        option 

config 'titi'
        list 
        list 

config 'tutu'
        list 
        list 

I want to replace each 2 new lines by only one when I display the file with cat.

I tried the following commands but they didn't work

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

the expected output is like this :

config 'toto'
        option 
        option 
config 'titi'
        list 
        list 
config 'tutu'
        list 
        list 
MLSC
  • 5,872
  • 8
  • 55
  • 89
Anis_Stack
  • 3,306
  • 4
  • 30
  • 53

5 Answers5

3

Using sed:

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

If your empty lines contain whitespace you can use

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

or

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

to filter them out as well.

Using awk:

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

Using grep:

$ grep -v '^[[:space:]]*$' foo.txt
Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71
3

With sed:

sed '/^$/d' file

(OR)

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

With tr:

tr -s '\n' < file
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
sat
  • 14,589
  • 7
  • 46
  • 65
1

Tiny little 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 
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
0
egrep -v '^ *$' YourFile

should be faster than sed

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43
-1

You can use a Bash while read loop.

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

Here, the loop will print every line that is not an empty string.

John B
  • 3,566
  • 1
  • 16
  • 20