문제

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 
도움이 되었습니까?

해결책

With sed:

sed '/^$/d' file

(OR)

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

With tr:

tr -s '\n' < file

다른 팁

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

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 
egrep -v '^ *$' YourFile

should be faster than sed

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top