Remove blank lines in a file using sed
Clash Royale CLAN TAG#URR8PPP
Remove blank lines in a file using sed
France 211 55 Europe
Japan 144 120 Asia
Germany 96 61 Europe
England 94 56 Europe
Taiwan 55 144 Asia
North Korea 44 2134 Asia
The above is my data file.
There are empty lines in it.
There are no spaces or tabs in those empty lines.
I want to remove all empty lines in the data.
I did a search Delete empty lines using SED has given the perfect answer.
Before that, I wrote two sed code myself:
sed -r 's/nn+/n/g' cou.data
sed 's/nnn*/n/g' cou.data
And I tried awk gsub, not successful either.
awk ' gsub(/nn*/, "n"); print ' cou.data
But they don't work and nothing changes.
Where did I do wrong about my sed code?
by default most sed and awk implementations work line by line, strip newline from input and add it back while printing.. so
n
is never going to match unless you use other features of sed/awk to have more than one line to work with– Sundeep
Aug 10 at 9:27
n
I suggest:
grep . file
– Cyrus
Aug 10 at 10:24
grep . file
maybe this can help unix.stackexchange.com/questions/180901/…
– Lino
Aug 10 at 14:31
sed '/^$/d' data
?– PesaThe
Aug 10 at 18:06
sed '/^$/d' data
1 Answer
1
Use the following sed
to delete all blank lines.
sed
sed '/./!d' cou.data
Explanation:
/./
!
d
cou.data
Where did you go wrong?
The following excerpt from How sed
Works states:
sed
sed operates by performing the following cycle on each line of input: first, sed reads one line from the input stream, removes any trailing newline, and places it in the pattern space. Then commands are executed; each command can have an address associated to it: addresses are a kind of condition code, and a command is only executed if the condition is verified before the command is to be executed.
When the end of the script is reached, unless the -n option is in use, the contents of pattern space are printed out to the output stream, adding back the trailing newline if it was removed.8 Then the next cycle starts for the next input line.
I've intentionally emboldened the parts which are pertinent to why your sed
examples are not working. Given your examples:
sed
sed
nn
nnn
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Possible duplicate of AWK remove blank lines
– oliv
Aug 10 at 9:10