0

I would like to move a path in a file to the top of the file. Each path is listed 1 per line. How do I move /someplace/2nd/ to the top using only the command line?

/someplace/1st/
/someplace/2nd/
/someplace/3rd/

So I end up with

/someplace/2st/
/someplace/1nd/
/someplace/3rd/
1
  • From the command line, it is always easier to generate a new file given an input file than to edit a file in place (change its contents). Is that good enough for you? After you've generated the new file you can always move it back to the original filename (thus squashing the original file).
    – Celada
    Jan 22, 2013 at 2:57

4 Answers 4

3

Since you used the vim tag I'll assume first that you meant Vim's command line. If that's the case, then this command will do it.

:g/^\/someplace\/2nd\/$/m0

where that last character is a zero. See

:help :g
:help :m

In the event that you meant the shell command line, you can use vim to edit your file using this command.

vim -c 'g/^\/someplace\/2nd\/$m0' -cwq yourfile

See

:help -c
:help :wq
2
  • :/^\/someplace\/2nd\/$/m0, without using :g, should be enough maybe with a shorter pattern.
    – romainl
    Jan 22, 2013 at 7:44
  • I was looking for the command line version. I used the pattern as romainl suggested. Works great. Going to update my script to use the vim command. Thank you both.
    – Jason
    Jan 23, 2013 at 5:06
4

The traditional way to edit files in place non-interactively is by using ed:

(echo '/^\/someplace\/2nd\/$/m0'; echo w; echo q ) | ed $file

That sends 3 commands to the ed text editor running on the file $file:

  • /regular_expression/m0: search for a line matching regular_expression and move it to position 0
  • w: write the file
  • q: quit
2
{
  sed -n '/^\/someplace\/2nd\//{p;q}' file
  sed    '/^\/someplace\/2nd\//d' file
} > temp && mv temp file
1

This might work for you (GNU sed):

sed -i '1,\|/someplace/2nd/|{1{h;d};//!{H;d};G}' file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .