Sed Explanation: sed '/./,$!d' file
sed '/./,$!d'
From the first line which contains a character (blank or not) to the end of the file - negate (which then means from the beginning of the file to the line before the first line which contains a character) - delete.
This deletes leading empty lines, not blank lines. To delete leading blank lines (lines which are empty or contain only whitespace characters) say '/\S/,$!d'
.
Read "Sed, an introduction and tutorial" at http://www.grymoire.com/Unix/Sed.html. Then read the reference manual at https://www.gnu.org/software/sed/manual/sed.html.
In short:
The general form of a
sed
command is [selector][negation]command[flags] (square brackets indicate optional parts)The selector, if present, selects the lines on which the command applies
If
!
appears it negates the selector, that is, makes the command apply to the lines which do not match the selector.If no selector is present the command applies to all lines.
A selector can select one line (by number) or a set of lines (by regular expression), or the lines between a start line (by number or regular expression) and an end line (by number or regular expression).
In our case the selector is
/./,$
which means from the first line found which matches/./
(that is, contains at least one character) to the end of the file ($
is used as a line number and means the last line in the file).It is negated by
!
, so that the command applies to the lines from the beginning of the file to the line before the first line matching/./
.The command
d
deletes the selected lines.
Related videos on Youtube
Emerson Peters
Updated on September 18, 2022Comments
-
Emerson Peters over 1 year
Could someone please explain this code that deletes all leading blank lines at the top of a file:
sed '/./,$!d' file
I understand that it is a regex, matching only the first character, but then don't understand the ,$!d part. Is this what it's being replaced by, or are they options for the match?
Is this even a search command if it does not start with 's/'...?
-
Emerson Peters over 7 yearsCould you please explain each thing individually?What does the comma do? I know the $ means the end of the string. I'm guessing the ! means the negate? How did it get to the point of defining the "beginning of the file to the line before the first line which contains a character" point?
-
Emerson Peters over 7 yearsI had both of those tabs open, but couldn't find a reference to these options/commands in the table of contents, or through a quick skim, so I didn't know where to look. It looks like I just need a more global understanding of sed first. Thank you for going into detail. I will use this as reference when studying later. :)