views:

21

answers:

2

Hi,

I want to add a word to field 1 of a file separated by space,for example

My file,containing two fields:

apple:fruit:tree
orange:fruit:tree
mango:fruit:tree
brinjal:vegetable:plant
potato:vegetable:root

now I want to add word "family" separated by space to the field 1.

Therefore, the resultant file should look some thing like this

apple family:fruit:tree
orange family:fruit:tree
mango family:fruit:tree
brinjal family:vegetable:plant
potato family:vegetable:root

Any ideas on this would be appreciated.

Thanks,

+2  A: 

Use can sed:

sed 's/:/ family:/' yourfile.txt

This will replace any : with family: which achieves the desired result. You might have to adjust the regular expression though, in case : also appears elsewhere in the text.

Update: I am not sure what you want with I want to add a word "active" to field 1 of a file separated by space as you give no example for that.

Update 2:
It will only replace the first occurrence of :. However, if you want to replace something in the middle, you just have to capture the data before the delimiter:

sed 's/^\(.*:.*\):/\1 family:/' test.txt

This example adds family before the third field. \(.*:.*\) captures the characters before and after the first : (i.e. the values of the first and second field). The following : will be replaced by this characters (\1 is referring to the first capture group) followed by family:. The rest of the line stays untouched.

Felix Kling
@Kling tankq ,but what if file contains 3 fields and i want to add "family" in the first field for example potato:vegetable:root, how can i solve dis
Shruti
@Shruti: Fleix's current solution will work even then as he is not doing the replacement globally.
codaddict
@Kling tanx its working...:)
Shruti
+2  A: 

Use awk

$ awk -F":" '{$1=$1" family"}1' OFS=":" file
apple family:fruit:tree
orange family:fruit:tree
mango family:fruit:tree
brinjal family:vegetable:plant
potato family:vegetable:root

If you want to add to 2nd field, just do $2=$2" family". Its easier than creating regex such as by using sed.

Now may i redirect you to awk manual to learn about awk. Try to do it yourself next time.

ghostdog74