Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete the lines starting with "//" (e.g., file header) which are at the beginning of a file?

Tags:

regex

shell

sed

awk

I want to delete the header from all the files, and the header has the lines starting with //.

If I want to delete all the lines that starts with //, I can do following:

sed '/^\/\//d'

But, that is not something I need to do. I just need to delete the lines in the beginning of the file that starts with //.

Sample file:

// This is the header
// This should be deleted
print "Hi"
// This should not be deleted
print "Hello"

Expected output:

print "Hi"
// This should not be deleted
print "Hello"

Update: If there is a new line in the beginning or in-between, it doesn't work. Is there any way to take care of that scenario?

Sample file:

< new empty line >
// This is the header
< new empty line >
// This should be deleted
print "Hi"
// This should not be deleted
print "Hello"

Expected output:

print "Hi"
// This should not be deleted
print "Hello"

Can someone suggest a way to do this? Thanks in advance!

Update: The accepted answer works well for white space in the beginning or in-between.

like image 890
Sweety Avatar asked Dec 23 '22 17:12

Sweety


2 Answers

Could you please try following. This also takes care of new line scenario too, written and tested in https://ideone.com/IKN3QR

awk '
(NF == 0 || /^[[:blank:]]*\/\//) && !found{
  next
}
NF{
  found=1
}
1
' Input_file

Explanation: Simply checking conditions if a line either is empty OR starting from // AND variable found is NULL then simply skip those lines. Once any line without // found then setting variable found here so all next coming lines should be printed from line where it's get set to till end of Input_file printed.

like image 146
RavinderSingh13 Avatar answered May 14 '23 22:05

RavinderSingh13


With sed:

sed -n '1{:a; /^[[:space:]]*\/\/\|^$/ {n; ba}};p' file
print "Hi"
// This should not be deleted
print "Hello"

Slightly shorter version with GNU sed:

sed -nE '1{:a; /^\s*\/\/|^$/ {n; ba}};p' file

Explanation:

1 { # execute this block on the fist line only
    :a; # this is a label
     /^\s*\/\/|^$/ { n;  # on lines matching `^\s*\/\/` or `^$`, do: read the next line
          ba }           # and go to label :a
};  # end block
p   # print line unchanged:
    # we only get here after the header or when it's not found

sed -n makes sed not print any lines without the p command.

Edit: updated the pattern to also skip empty lines.

like image 38
Lev Levitsky Avatar answered May 14 '23 22:05

Lev Levitsky