Summary: substitution/replace a field in a file

From: Zaigui Wang <zaigui_at_yahoo.com>
Date: Fri Nov 15 2002 - 18:11:34 EST
I got quite a few good solutions, thanks to the
following (my apology in advance if I missed anyone
here):

Alex Ugolini
Trucks, Jesse
ChinTu
Deiss, Mark
marco.breedeveld
Fabrice Guerini
John Leadeham
Ramji Venkateswaran

Most provided good, possibly working, solutions. Two
of the best solutions are provided by Alex and
Fabrice. Here they are:

Solution 1 
(BY Fabrice. Mark provided similar solution):
search for each field with the \([^ ]*\) and restore
it with the positional reference "\number", such as:

server [~/tmp] cat /tmp/y
first1 second1 third1 %\/&;:@!~.,?

server [~/tmp] sed -e 's/^\([^ ]*\) \([^ ]*\) \([^
]*\) \([^ ]*\)/\1 \2 \3 foo/' /tmp/y
first1 second1 third1 foo

Solution 2
(BY Alex. ChinTu and Ramji had similar solution):
use awk and change the value on the fly. You can embed
a variable into the awk command without having to
worry about quoting issue. For example:

matrix> name=idiot
matrix> cat /tmp/test
who are you \|~@:&%$^ huh?
matrix> awk '{$4=new;print $0}' new=$name /tmp/test
who are you idiot huh?
matrix>

Alex sums this up quite nicely:
-------
There are two ways of passing shell variables into an
awk script.

One way is with the -v flag.  (This may only work with
"nawk" compatible awk's.)

awk -v nv="$newval" '{$4 = nv; print $0}' infile >
outfile

This way, the awk variable "nv" is known in the awk
script from the beginning of execution.  (So, it can
be used in the BEGIN action, for example.)

A different way to assign awk variables from the
command line is to mix them with filenames:

awk '{$4 = "new_4th_field"; print $0}' f=1 infile f=2
otherinfile > outfile

This sets the variable "f" to "1", then reads through
"infile".  When awk hits end-of-file on infile, it
changes "f" to "2", then it reads through
"otherinfile".

This technique can be very useful at times.  In the
above example, it can tell the program which input
file is being processed:

awk '...' f=load f1.cfg log.cfg src.cfg f=proc indata1
deptdata > out

Here, when f == "load", we are loading .cfg files. 
When f changes to "proc", we are loading data files. 
This is easier than referencing "FILENAME".
---------

Thank you all.
Yahoo! Web Hosting - Let the expert host your site
http://webhosting.yahoo.com
_______________________________________________
sunmanagers mailing list
sunmanagers@sunmanagers.org
http://www.sunmanagers.org/mailman/listinfo/sunmanagers
Received on Fri Nov 15 18:15:28 2002

This archive was generated by hypermail 2.1.8 : Thu Mar 03 2016 - 06:42:58 EST