Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete empty lines and trim surrounding spaces in Bash

Tags:

This command removes empty lines:

sed -e '/^$/d' file 

But, how do I remove spaces from beginning and end of each non-empty line?

like image 714
alvas Avatar asked Dec 19 '11 14:12

alvas


People also ask

How do you grep an empty line?

To match empty lines, use the pattern ' ^$ '. To match blank lines, use the pattern ' ^[[:blank:]]*$ '. To match no lines at all, use the command ' grep -f /dev/null '.


2 Answers

$ sed 's/^ *//; s/ *$//; /^$/d' file.txt  `s/^ *//`  => left trim `s/ *$//`  => right trim `/^$/d`    => remove empty line 
like image 173
kev Avatar answered Sep 19 '22 03:09

kev


Even more simple method using awk.

awk 'NF { $1=$1; print }' file 

NF selects non-blank lines, and $1=$1 trims leading and trailing spaces (with the side effect of squeezing sequences of spaces in the middle of the line).

like image 34
M.S. Arun Avatar answered Sep 20 '22 03:09

M.S. Arun