1

How can I move lines containing specific strings (ie. 005, and 007) to the top of the target file?

Contents of target file:

XXX_008
XXX_001
XXX_002
XXX_009
XXX_003
XXX_006
XXX_005 ----> located here
XXX_007 ----> and here
XXX_004

How can I move lines XXX_005 and XXX_007 to the top? Retaining the rest of the files order? Like so:

XXX_005 ----> now here
XXX_007 ----> and here
XXX_008
XXX_001
XXX_002
XXX_009
XXX_003
XXX_006
XXX_004

all the rest retain the same order they were originally in.

... it would be nice to be able to only specify only the numbers when moving lines since I always use double zero padded numbers like any-name_001, any-name_002, etc.

Is this possible somehow?

0

try with:

<file gawk '/_005/,/_007/ {
  top[i++]=$0
  next
}
{
  botom[j++]=$0
}
END {
  for(k in top)
    print top[k]
  for(k in botom)
    print botom[k]
}'
0

first cat the lines with matched pattern, then those with revert matched pattern:

cat <(grep -x 'XXX_00[57]' infile) <(grep -xv 'XXX_00[57]' infile)

note: as you mentioned move lines with specific above pattern, then you may need to remove -x option from the command which that is used to match that pattern as in whole line.

  • 3
    Or just { grep -x 'XXX_00[57]' infile; grep -xv 'XXX_00[57]' infile; } > outfile – Stéphane Chazelas May 16 at 11:49
  • @StéphaneChazelas thanks, this is better and more compatibility. – αғsнιη May 17 at 4:26
0

With GNU sed alongwith it's extended regex engine enabled, we can do the problem. The hold space contains all the lines that need to be moved north, while the pattern space contains the nonmatching lines.

$ sed -Ee '
    /_005|_007/{
      /\n/!{
        H;$!d;g;s/.//;b
      }
      G
      s/(.*\n.*)(\n.*)(\n\n.*)/\1\3\2/
      h;s/.*\n(\n)/\1/
      x;s/\n\n.*//
      $bend
      s/^/\n/;D
    }
    $bend
    N;s/^/\n/;D
    :end
    x;G;s/.//
' input.txt

With perl we maintain two arrays to store the matching nd nonmatching lines:

$ perl -ne 'push @{/_005|_007/ ? \@A : \@B}, $_}{print @A, @B' input.txt

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.