Computing.Net > Forums > Unix > Adding a new string in a file

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.

Adding a new string in a file

Reply to Message Icon

Name: vijay.goriya
Date: March 6, 2008 at 03:51:50 Pacific
OS: Unix
CPU/Ram: 512
Product: dell
Comment:

HI,

My file contains the data like
john smitch Tracy -tcopse
I have to add a new string "PETER"at the 4th posion so the file shud contain the data like:
john smitch Tracy PETER -tcopse
please lemme know how it can be done...



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: March 6, 2008 at 06:57:00 Pacific
Reply:

One of the other guys will give you an awk or perl solution, but this one uses the shell:


#!/bin/ksh

newvar="PETER"
while read f1 f2 f3 fr
do
echo "f1 $f2 $f3 $newvar $fr"
done < file.txt



0

Response Number 2
Name: Rajam
Date: March 7, 2008 at 02:48:23 Pacific
Reply:

This statement helps you to add a new string in a file.
cat filename | awk '{print $1,$2,$3,"PETER",$4}' >Output

Thanks
Rajam


0

Response Number 3
Name: nails
Date: March 7, 2008 at 09:59:06 Pacific
Reply:

Rajam:

Your awk script works only for lines with 4 fields. If more the 4 fields exist, then the fields need to be shifted. (My original shell solution doesn't have this issue). This script works for any number of fields:


#!/bin/ksh

awk ' BEGIN { pos=4; newvar="PETER" }
{
for(i=1;i<=NF;i++)
{
if (i == pos)
{
savevar=$pos
$pos=newvar
}

if (i > pos)
{
buffer=$i
$i=savevar
savevar=buffer
}

if (i == NF)
savestr=$0" "savevar
}
print savestr
} ' filename


0

Response Number 4
Name: vijay.goriya
Date: March 12, 2008 at 01:20:16 Pacific
Reply:

Thnx alot Nails...this is what i was looking for...


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More


Connection string for SQL... Find match in two diff fi...



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: Adding a new string in a file

change string in multiple file www.computing.net/answers/unix/change-string-in-multiple-file/4697.html

Insert string in a txt file..? www.computing.net/answers/unix/insert-string-in-a-txt-file/6089.html

Find and Change String in File www.computing.net/answers/unix/find-and-change-string-in-file/4628.html