Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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/
share|improve this question
    
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 '13 at 2:57

4 Answers 4

up vote 3 down vote accepted

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
share|improve this answer
    
:/^\/someplace\/2nd\/$/m0, without using :g, should be enough maybe with a shorter pattern. –  romainl Jan 22 '13 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 '13 at 5:06

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
share|improve this answer
{
  sed -n '/^\/someplace\/2nd\//{p;q}' file
  sed    '/^\/someplace\/2nd\//d' file
} > temp && mv temp file
share|improve this answer

This might work for you (GNU sed):

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.