LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [bash] transfer last line to first place (https://www.linuxquestions.org/questions/programming-9/%5Bbash%5D-transfer-last-line-to-first-place-926467/)

Alexos 01-30-2012 05:00 AM

[bash] transfer last line to first place
 
I want to transfer last line in the file to the first place, without processing all file. Is it possible?
For example if I have
Code:

Line 1...
Line 2...
....
Line n-1...
Line n...

I want to receive
Code:

Line n...
Line 1...
Line 2...
....
Line n-1...

Or if it is impossible, how can I get
Code:

Line n...
Line 2...
...
Line n-1...


colucix 01-30-2012 05:45 AM

Maybe using something like
Code:

cat <(tail -n1 file) <(head -n-1 file)
this requires redirecting the output to a temporary file and rename it later. How many lines are in the file?

Alexos 01-30-2012 06:30 AM

Quote:

Originally Posted by colucix (Post 4588146)
How many lines are in the file?

unknown

Alexos 01-30-2012 07:10 AM

OK, solved)
Code:

size=`wc -l file.in | awk '{print $1}'`
let size--
cat <(tail -1 file.in) <(head -$size file.in) > file.out


colucix 01-30-2012 08:45 AM

Nice! Actually the size calculation is not necessary since option -n of the head command accepts negative numbers to print all but the last N lines of each file. Specifying
Code:

head -n-1
as in my example, will exclude the last line of the file independently from the total length. My concern about the number of lines was related only to performance.

Alexos 01-31-2012 04:46 AM

Great! thanks. but I found easier method again) without creating new files
Code:

total=`tail -n 1 "file"`
sed -i -e '$d' -e "1c\\$total\n" "file"


firstfire 01-31-2012 06:31 AM

Hi.

Here is even simpler solution:
Code:

$ cat infile2.txt
Line 1...
Line 2...
....
Line n-1...
Line n...
$ echo -e '$m0\nw' | ed infile2.txt
47
47
$ cat infile2.txt
Line n...
Line 1...
Line 2...
....
Line n-1...



All times are GMT -5. The time now is 11:55 AM.