I need to remove all lines that contain spaces in a file. I know very little bash. Any help would be greatly appreciated.

Dani AI

Generated

: and pointed out a simple grep-based approach (invert-match). That is fine for a quick one-off, but here are a few alternatives and practical notes so the result matches intent (literal space vs any whitespace) and is safe to apply to a real file.

For any-whitespace (spaces, tabs, etc.) use POSIX character classes; for example, sed or awk can delete lines that contain whitespace anywhere. These commands stream the file (no full-file memory) and are suitable for large files.

sed '/[[:space:]]/d' inputfile > outputfile
awk '!/[[:space:]]/' inputfile > outputfile

If the goal is to drop only lines that are entirely blank or entirely whitespace, use a start-to-end pattern:

sed '/^[[:space:]]*$/d' inputfile > outputfile

Avoid editing the original in place without a backup. GNU sed supports -i for in-place edits but its behavior differs on BSD/macOS; consult the sed manual before using -i. For safe workflow, write to a temporary file and move it over the original, or keep a backup copy first. See the GNU sed documentation for options and portability details: GNU sed manual. For more on awk patterns and performance, see the gawk manual: Gawk manual.

Recommended Answers

All 2 Replies

Probably the easiest way could be to pipe your file through grep(1).
Assuming the file in question is named "YOURFILE" try

cat YOURFILE | grep -v " "

at your favorite shell prompt.
Pls note the single blank between the double quotes.

;) grep -v " " file

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.