If you have GNU sed (so non-embedded Linux or Cygwin):
sed '/bar/,+1 d'
If you have bar
on two consecutive lines, this will delete the second line without analyzing it. For example, if you have a 3-line file bar
/bar
/foo
, the foo
line will stay.
The easiest way to do this is with the rectangle commands.
Go to the first line of the buffer (or more generally the first line where you want to insert text) and move to the column where you want to insert the text. Go to the last line and move to the same column (there's no built-in way to do that). Type C-x r t
(string-rectangle
) and type the string you want to insert.
You can use the following function to move the cursor to the same column as the mark:
(defun move-to-mark-column ()
(interactive "@")
(move-to-column (save-excursion
(goto-char (mark))
(current-column))))
If you want to move to a column by number, there's move-to-column
: C-u 42 M-x move-to-column RET
. Unless you bind this to a key, it's shorter to move to the beginning of the line and then by character count (Home C-u 42 Right
), but this can move to the next line if the count is too high, whereas move-to-column
leaves you at the end of the line in this case. Also move-to-column
behaves differently if there are tabs or split lines.
If the point and mark aren't on the same column, they're opposite corner of a rectangle. The rectangle command affect all the characters inside that rectangle. string-rectangle
erases the rectangle and puts the specified text on each line instead. C-x r d
erases the rectangle. You can also copy-paste (C-x r M-w
, C-x r k
, C-x r y
to copy/kill/yank) and insert or fill with rectangles (C-x r o
, C-x r c
to open/clear with spaces), and more.
Best Answer
You can use
sed
:Thanks to Stephane and Marco's comments, note that the
-i
option isn't POSIX. A POSIX way to do the above would beor
perl
:Explanation
Both commands perform a regex substitution, replacing the beginning of a line (
^
) with your desired string. The-i
switch in both commands makes sure the file is edited in place (i.e. the changes are reflected in the file instead of printed to stdout).sed
should be available on any POSIX-compliant OS andperl
should be available on most modern Unices except perhaps for the ones that have gone through the effort of removing it.