Skip to main content

Quickest way to move a line in a text file before another line in a text file? [Resolved]

I have the line number 55 in a text file which I want to move just before line number 23 in the same text file. I know that you can move lines up by a certain number of lines 1, 2 but is it possible to append or prepend a line to another line instead of the verbose way of moving lines up or down a textfile?

I am open to answers using vim, sed or any other command line tool but the more concise the better


The sed command i inserts text before a line which is similar to what I am looking for except that I want to insert a line before a line

Question Credit: MyWrathAcademia
Question Reference
Asked July 21, 2019
Posted Under: Unix Linux
2 Answers

A scriptable editor makes this pretty straight-forward!

printf '%s\n' '55m22' 'wq' | ed -s input

This sends two commands to ed (editing the file named input):

  1. 55m22 -- move line 55 after line 22
  2. wq -- save the file back to disk and quit.

credit: Jeff Schaller
Answered July 21, 2019

A little shorter:

ex input <<<"55m22|wq"

credit: steve
Answered July 21, 2019
Your Answer