How to delete blank lines?

QuestionsQuestions8 SkillsProBasic Files OperationsSep, 04 2025
0194

To delete blank lines from a file in Bash, you can use the sed command. Here’s how to do it:

Using sed

To delete all blank lines from a file named file.txt, use:

sed -i '/^$/d' file.txt

Explanation:

  • sed: Stream editor for filtering and transforming text.
  • -i: Edits the file in place.
  • /^$/: A regular expression that matches empty lines (lines with no characters).
  • d: Command to delete the matched lines.

Alternative Using grep

You can also use grep to achieve the same result:

grep -v '^$' file.txt > temp.txt && mv temp.txt file.txt

Explanation:

  • grep -v '^$': This command outputs all lines that do not match the empty line pattern.
  • > temp.txt: Redirects the output to a temporary file.
  • mv temp.txt file.txt: Replaces the original file with the modified one.

Feel free to ask if you have more questions or need further clarification!

0 Comments

no data
Be the first to share your comment!