1

How to move lines containing specific text to top of file in same order as code executed?

Here is the code I have:

printf 'g?_001\|_002\|_003\|_004\|_005?m0\nwq\n' | ed -s target_file

( credit goes to steeldriver for helping me get this far. Truely an amazing user of this site! )

This moves them to the top like so:

name_003
name_005
name_004
name_002
name_001

or however order they were in originally, just to the top.

but I need them to be put in the same order as I have them in within the printf and ed code, so in this case, like:

name_001
name_002
name_003
name_004
name_005

Anyone familiar with printf and ed?

2

Use separate move commands:

ex -sc 'g?_005?m0' -c 'g?_004?m0' -c 'g?_003?m0' -c 'g?_002?m0' -c 'g?_001?m0' -c wq target_file

Note that:

  • I'm using ex (actually, Vim) here, not ed. You can specify the ex-commands in the command line using the -c option, so printf isn't needed.
  • The patterns must be in reverse order (005 gets moved to the top first, then 004, pushing down 005, then 003, pushing down both 004 and 005, ...)

With printf and ed, maybe:

(printf 'g?%s?m0\n' {005..001}; printf 'wq\n') |
  ed -s target_file
  • The ex command does not work for me :/ it simply doesn't have any effect when used. I am running Arch Linux Manjaro. – Anonymous May 16 '19 at 6:04
  • Works fine enough for me. What was the actual command you used, and the actual input you provided? – muru May 16 '19 at 6:05
  • With Arch Linux, ed is GNU ed, but ex is probably heirloom vi. Try installing Vim and using it instead. – muru May 16 '19 at 6:06
  • It's saying '-sc' is not a valid file – Anonymous May 16 '19 at 6:06
  • When I use vim rather than ex. It says VIM - Vi IMproved 8.1 (2018 May 18, compiled Mar 29 2019 20:08:59) Garbage after option argument: "-sc" More info with: "vim -h" – Anonymous May 16 '19 at 6:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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