1751867 Members
5259 Online
108782 Solutions
New Discussion юеВ

Script Help

 
Patrick Murphy
Advisor

Script Help

I have a file with contains many lines with the work RESTART separated by other stuff. It is like this:

stuff
RESTART 0
stuff
stuff
RESTART 0
stuff
stuff
RESTART 0
stuff


In need to locate the last RESTART in the file and change the zero that follows it to a 2. All other lines with RESTART should remain unchanged. Please no Perl solutions.

Can someone help?
7 REPLIES 7
Jonathan Fife
Honored Contributor

Re: Script Help

Quick n dirty:

lastline=$(grep -n RESTART filename| tail -1 | cut -d: -f1)
awk -vll=$lastline '{if (NR==ll) print "RESTART 2"; else print $0}' filename
Decay is inherent in all compounded things. Strive on with diligence
Zinky
Honored Contributor

Re: Script Help

Here's a plain and simple solution using "ed" - the standard UNIX editor:

Put in a script:

ed - file <
Hakuna Matata

Favourite Toy:
AMD Athlon II X6 1090T 6-core, 16GB RAM, 12TB ZFS RAIDZ-2 Storage. Linux Centos 5.6 running KVM Hypervisor. Virtual Machines: Ubuntu, Mint, Solaris 10, Windows 7 Professional, Windows XP Pro, Windows Server 2008R2, DOS 6.22, OpenFiler
Sandman!
Honored Contributor

Re: Script Help

Here's a way to do it with ex(1):

# ex -s +"$(sed -n '/RESTART/=' infile)s/0/2/p | x" infile

~cheers
Hein van den Heuvel
Honored Contributor

Re: Script Help

It's tempting to make tow passes through the file, like Jonathan shows. AWK could do that readily.

If it is not too much data (less than 10MB?) then why not suck it into an array, and remember the element with the last 'RESTART'. At end fix that element and print all:


awk 'END {l[r]="RESTART 2"; while (i++ < NR) { print l[i]}} {l[NR]=$0} /^RESTART 0/{ r=NR}' old.txt > new.txt

Good luck,
Hein.

Zinky
Honored Contributor

Re: Script Help

ed - file <
Hakuna Matata

Favourite Toy:
AMD Athlon II X6 1090T 6-core, 16GB RAM, 12TB ZFS RAIDZ-2 Storage. Linux Centos 5.6 running KVM Hypervisor. Virtual Machines: Ubuntu, Mint, Solaris 10, Windows 7 Professional, Windows XP Pro, Windows Server 2008R2, DOS 6.22, OpenFiler
Patrick Murphy
Advisor

Re: Script Help

Thanks Jonathan it worked great.
Patrick Murphy
Advisor

Re: Script Help

Jonathan's work the best for my situation. Thanks all for your help.