0

I want to get delete all of the blank lines and lines with spaces (if any exist (ONLY from the bottom of the file)) and then to remove one more line (also ONLY from the bottom of the file).

I have this code:

while [[ "$last_line" =~ ^$ ]] || [[ "$last_line" =~ ^[[:space:]]+$ ]]
do
    sed -i -e '${/$/d}' "./file.txt"
done
    sed -i -e '${/$/d}' "./file.txt"

For some reason the loop doesn't stop and it deletes everything in the file. What is the matter?

2
  • 2
    You're not changing the value of $last_line within the loop, so how could it stop? Commented Aug 5, 2015 at 11:42
  • Wow, I have forgotten about that, thank you, works great! Commented Aug 5, 2015 at 11:46

1 Answer 1

2

You can use tac and awk combination for this:

tac file | awk 'BEGIN{p=0} p<=1 && /^[[:blank:]]*$/{p=1; next} p==1{p++; next} 1' | tac

tac file         # prints files in reverse
/^[[:blank:]]*$/ # will find all blank/empty lines using search pattern    
tac              # reverse the file content
Sign up to request clarification or add additional context in comments.

3 Comments

I never heard of tac before (and it's not on OSX Terminal). So I logged into a linux box and looked up the man page... Basically it's cat in reverse. I guess that is pretty obvious in retrospect :D
Hmm I am also on OSX but I have installed all gnu utils using home brew hence tac is there for me.
I didn't know that was a package - top tip! I remember having some trouble with some of the BSD-flavoured utils in the past - missing flags etc. Thanks @anubhava

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.