Reputation: 20139
How can I match a pattern only at the start of a file? In my particular usecase I have a script with a bunch of comments in the header and potential comments in the body, and I only want to remove the header comments.
# blah blah
# More blah
# Hello World
Actual stuff
# commented out stuff
More stuff
Should map to
Actual stuff
# commented out stuff
More stuff
The regex I've tried is /^#.*$//mg
, but this will match the comments in the body as well. How can I restrict it to only the comments in the header? Additionally, I don't want to leave blank lines at the head of the file.
Upvotes: 0
Views: 50
Reputation: 89639
With sed:
sed -n '1{:a;/^#/n;/^#/ba};p' file.txt
details:
1 # if the line number is 1
{ # do
:a; # define the label a
/^#/n; # when the line begins with # load the next line in pattern space
/^#/ba # if the "new" line begins with # go to label a
};
p # print the line
With the n
parameter, the lines are no more automatically printed.
Upvotes: 1
Reputation: 786091
You can use this awk:
awk '/^[^#]/{body=1} body' file
Actual stuff
# commented out stuff
More stuff
Upvotes: 1