Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

swap lines in a file

Status
Not open for further replies.

midge25

Programmer
Jul 19, 2002
9
Hi,

I'm hoping someone can help.

I need to cut the 2nd to last line from a file and paste it to the top of the file.

For example:

Line1
Line2
Line3
Line4

Needs to change to

Line3
Line1
Line2
Line4

Thanks in advance,
midge25
 
Are the contents of 2nd last line always the same, and are they unique to the file ? Dickie Bird
db@dickiebird.freeserve.co.uk
 
Dickie Bird

The contents of teh 2nd last line are always different.

Tried the following and it works but is quite slow:

export header=`tail -2 ${file_name} | head -1`
sed -n "/$header/p" ${file_name} > temp1 | sed "/$header/d" ${file_name} >> temp1

Thanks

midge25
 
Thats about what I'd have produced - But someone will have a neater,quicker solution, for sure !
[wavey] Dickie Bird
db@dickiebird.freeserve.co.uk
 
Here's one way to do it using ex

ex - file << EOF
\$-mo0
wq
EOF

CaKiwi
 
function swap(arra,i,m) {
tmp = arra
arra = arra[m]
arra[m] = tmp
}

function parray(array,max) {
while (i <= max) {
i++
print array
}
}

BEGIN {
print ARGV[1]
while ((getline arr[a++] < ARGV[1]) > 0) {
#print a
}
close(ARGV[1])

print &quot;First: &quot; ,arr[1], &quot;Second to last: &quot;, arr[a - 2]
swap(arr,1,(a - 2))
parray(arr,a)
}

Last try to submit this. These sites would be better hosted on *nix.
 
Sorry, You wanted the output bumped down a line each, so
swapping isn't the only thing you need to do.

Here is the correction:

function swap(arra,i,m) {
tmp = arra
arra = arra[m]
arra[m] = tmp
}

function bump(array,n,max,val) {
tmp = array[n + 1]
array[n + 1] = val
n++
if (n < max) {
bump(array,n,max,tmp)
}
}

function parray(array,max) {
while (i <= max) {
i++
print array
}
}


BEGIN {
#print ARGV[1]
while ((getline arr[a++] < ARGV[1]) > 0) {
#print a
}
close(ARGV[1])

print &quot;First: &quot; ,arr[1], &quot;Second to last: &quot;, arr[a - 2]
swap(arr,1,(a - 2))
bump(arr,1,(a + 1),arr[a - 2])
parray(arr,a)
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top