0

Sample input file:

abcd
<Space>
1234
<Space>

Desired output:

abcd
1234
αғsнιη
  • 41,407

3 Answers3

1

Pass it through

sed '/^[[:blank:]]*$/d'

This sed command deletes all lines that are empty or that only contains spaces and/or tabs. The regular expression ^[[:blank:]]*$ matches the empty/blank lines, and the trailing d is a sed editing command that deletes them.

For example:

sed '/^[[:blank:]]*$/d' <file >newfile

The file newfile will be the edited variant of file with the empty lines removed.

Alternatively, only output the lines with non-blank characters on them:

sed -n '/[^[:blank:]]/p' <file >newfile

This prints each line that contains at least one character that is not space or tab. The rest of the lines are ignored. The -n option to sed disables the default output of every line, and the trailing p is the sed command that outputs the current line (if it matches the preceding regular expression).

Kusalananda
  • 333,661
0

if you want to get rid of lines containing only spaces, as well as empty lines:

grep '[^ ]'   # ie, match any lines with at least 1 char different from space

alternatively :

grep -v '^ *$' # ie, hide lines that only contain spaces (0 or n spaces, ie empty lines as well)

if you want to also get rid of empty lines or lines with just "tabs or spaces"

grep -v "^[ $(printf '\t')]*$"
0

Mandatory awk-based solution:

awk 'NF' input.txt

This will only print lines where awk detects at least one "field" (i.e. the field counter NF is non-zero). Note that this will also remove lines which are empty in the sense that they only contain whitespace.

AdminBee
  • 22,803