Computing.Net > Forums > Unix > Replace a field content

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Replace a field content

Reply to Message Icon

Name: n
Date: October 28, 2003 at 13:28:03 Pacific
OS: os
CPU/Ram: 1
Comment:

Hi all,

I have the following comma separated file:

line1,45,apple
line2,33,orange
line3,12,lemon

I need a script that will replace field 2 with 100. i.e. my expected result is:

line1,100,apple
line2,100,orange
line3,100,lemon

I am successful using the awk command {print $1",100,"$3}, but is there a better way? Please advise. Thanks.



Sponsored Link
Ads by Google

Response Number 1
Name: Nails
Date: October 28, 2003 at 16:44:44 Pacific
Reply:

Hi:

Awk is a good choice for a tool. You can also change the record separater, set field 2 to 100, and print the whole line:

awk ' BEGIN { FS=","; OFS="," }
{
$2=100
print $0
} ' data.file

Not better, but different.

Regards,

Nails


0

Response Number 2
Name: Frank
Date: October 29, 2003 at 08:00:22 Pacific
Reply:

Hi
something without awk would be

IFS=','
{ while read a b c
do
echo "$a,100,$c"
done } < obst.txt
IFS='
'

Cheers Frank


0

Response Number 3
Name: nails
Date: October 29, 2003 at 09:35:04 Pacific
Reply:

Hi:

You can save yourself the trouble of restoring field seperator IFS by doing this:

while IFS="," read a b c
do
echo "$a,100,$c"
done < obst.txt

Regards,

Nails


0

Response Number 4
Name: FishMonger
Date: October 29, 2003 at 15:49:53 Pacific
Reply:

Here's how to do it with a perl command.

perl -pi -e 's/,\d+/,100/' obst.txt


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: Replace a field content

Replace one digit within a field www.computing.net/answers/unix/replace-one-digit-within-a-field/8318.html

finding length of a field in shell www.computing.net/answers/unix/finding-length-of-a-field-in-shell/7053.html

Passing a field separator literally www.computing.net/answers/unix/passing-a-field-separator-literally/4656.html