Copy line and insert it in a new position with sed or awk
With ed
:
$ printf '$t0\n,p\n' | ed -s file
f
a
b
c
d
e
f
The t
command in ed
transfers/copies a line from the addressed line (here $
for the last line) to after the line addressed by its argument (here 0
, i.e. insert before the first line). The ,p
command prints the contents of the editing buffer (change this to w
to write the result back into the file).
or simply like this, without sed or other
tail -1 list && cat list
Pure sed
:
sed 'H;1h;$!d;G' file.txt
All lines are collected in the hold space, then appended to the last line:
H
appends the current line to the hold space. Unfortunally this will start the hold space with a newline, so1h
for the first line, the hold space gets overwritte with that line without preceeding newline$!d
means if this is not (!
) the last line ($
),d
elete the line, because we don't want to print it yetG
is only executed for the last line, because for other lines thed
stopped processing. Now all lines (first to last) we collected in the hold space get appended to the current (last) line with theG
command and everything gets printed at the end of the script.