user137369
user137369

Reputation: 5686

Reorder lines with a specific pattern in a text file

I have a file that goes something like:

{{}} line 1
{{}} line 2
line 3
line 4
{{}} line 5
line 6

What I want to do is move the last line of the file prefixed by {{}} to be after the second to last line with {{}}, so the end result would be:

{{}} line 1
{{}} line 2
{{}} line 5
line 3
line 4
line 6

It has to be bash (calling sed, perl, head, or other commands, is fine).

Upvotes: 0

Views: 195

Answers (3)

captcha
captcha

Reputation: 3756

Code for GNU :

sed -n 's/^\({{}}\)/\1/p;tk;H;:k;${x;s/\n//;p};d' file

$cat file
{{}} line 1
{{}} line 2
line 3
line 4
{{}} line 5
line 6

$sed -n 's/^\({{}}\)/\1/p;tk;H;:k;${x;s/\n//;p};d' file
{{}} line 1
{{}} line 2
{{}} line 5
line 3
line 4
line 6

Upvotes: 2

mpapec
mpapec

Reputation: 50637

If line begins with {{}}, print it else save it for later,

perl -ne 'if (/^\Q{{}}/) {print}else{push @r,$_} }{print @r' file

Upvotes: 3

jaypal singh
jaypal singh

Reputation: 77095

One way with awk:

awk '$1!="{{}}"{move[++i]=$0;next}1 END{for(x=1;x<=length(move);x++)print move[x]}' file

Upvotes: 3

Related Questions