Linux Grep/Sed Certain Lines - Space Removal

Remove empty lines in a text file via grep

grep . FILE


(And if you really want to do it in sed, then: sed -e /^$/d FILE)

(And if you really want to do it in awk, then: awk /./ FILE)

Remove tabs and blank lines with grep/sed/tr

You probably don't have GNU Sed. With GNU Sed your sed command should work.

There is another solution that you could try out:

sed -e 's/^[[:space:]]*//' -e '/^$/d' test.txt

or, to just remove use spaces and tabs:

sed -e 's/^[ \t]*//' -e '/^$/d' test.txt

How to print a file, excluding comments and blank lines, using grep/sed?

With grep:

grep -v '^\s*$\|^\s*\#' temp

On OSX / BSD systems:

grep -Ev '^\s*$|^\s*\#' temp

How to delete from a text file, all lines that contain a specific string?

To remove the line and print the output to standard out:

sed '/pattern to match/d' ./infile

To directly modify the file – does not work with BSD sed:

sed -i '/pattern to match/d' ./infile

Same, but for BSD sed (Mac OS X and FreeBSD) – does not work with GNU sed:

sed -i '' '/pattern to match/d' ./infile

To directly modify the file (and create a backup) – works with BSD and GNU sed:

sed -i.bak '/pattern to match/d' ./infile

Delete empty lines using sed

You may have spaces or tabs in your "empty" line. Use POSIX classes with sed to remove all lines containing only whitespace:

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

A shorter version that uses ERE, for example with gnu sed:

sed -r '/^\s*$/d'

(Note that sed does NOT support PCRE.)

Remove blank lines with grep

Try the following:

grep -v -e '^$' foo.txt

The -e option allows regex patterns for matching.

The single quotes around ^$ makes it work for Cshell. Other shells will be happy with either single or double quotes.

UPDATE: This works for me for a file with blank lines or "all white space" (such as windows lines with \r\n style line endings), whereas the above only removes files with blank lines and unix style line endings:

grep -v -e '^[[:space:]]*$' foo.txt

SED Command to remove first digits and spaces of each line

Your sed command would be,

sed 's/.* //g' file

This would remove the first numbers along with the space followed.



Related Topics



Leave a reply



Submit