With sed
:
sed '/^$/d' file
(OR)
sed '/^[ ]*$/d' file
With tr
:
tr -s '\n' < file
Frage
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
Lösung
With sed
:
sed '/^$/d' file
(OR)
sed '/^[ ]*$/d' file
With tr
:
tr -s '\n' < file
Andere Tipps
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.