I was wondering if there's any command to look for blank field values of a text file and remove the entire line.
Example
Hello:Its Me
Hello:How are you
Hello:
Hello:Bye
And expected output
Hello:Its Me
Hello:How are you
Hello:Bye
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityI was wondering if there's any command to look for blank field values of a text file and remove the entire line.
Example
Hello:Its Me
Hello:How are you
Hello:
Hello:Bye
And expected output
Hello:Its Me
Hello:How are you
Hello:Bye
Very standard case, the simplest solution with awk
would be
awk -F: '$2 != ""' file
and with grep
:
grep :. file
If you mean to skip Hello:
lines you can use something like:
awk -F: '{if($2 != "") print }' input_file
At least with GNU awk, and I think with any version of awk, the default action when something evaluates to true
is to print. So, if you set the field delimiter to :
, to print lines that have a second field, all you need is:
$ awk -F: '$2' file
Hello:Its Me
Hello:How are you
Hello:Bye
However, this will also print cases where the second field is whitespace (a space, or a tab etc), but will not print the line if second field is one or multiple 0
s, because awk
evaluates this as false.
Sometimes it is easier to define the remove conditions (grep -v
). Example remove when last field is empty:
grep -v ':$' file