Skip to main content

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

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?


Question Credit: Anonymous User
Question Reference
Asked May 16, 2019
Posted Under: Unix Linux
44 views
1 Answers

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

credit: muru
Answered May 16, 2019
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA