Copying a single value to the entire column

Hello everone,

I have a text file as input, which lokks like for exemple:

#     #    #
12   2    3
12
12
12
12
12
12
12

It has three column. My question is, i want to copy the value of 2nd column, 1st row to the entire 2nd column. similarly for the third column also. My result should look like:

#     #     #
12   2     3
12   2     3
12   2     3
12   2     3
12   2     3
12   2     3
12   2     3
12   2     3

Actually i am dealing with large number of rows and columns and the values are automatically generated. I would e very glad if any one could help me to solve this problem. Thanks :slight_smile:

Hello dinesh.n,

Welcome to forum, following may help you in same.

awk 'NR==1{A=$2 OFS $3;print;next}{;$0=$0 OFS A;print}' Input_file
 

Output will be as follows.

12 2 3
12 2 3
12 2 3
12 2 3
12 2 3
12 2 3
12 2 3
12 2 3
 

EDIT: Adding one more solution to same.

awk '{$2=NF>1?$2:A;$3=NF>2?$3:B;A=$2;B=$3} 1'  Input_file
 

Thanks,
R. Singh

1 Like

Please use code tags as required by forum rules!

How about

awk 'NR==2 {split ($0, T); MX=NF} NR>2 {for (i=2; i<=MX; i++) $i=T} 1' file
# # #
12 2 3
12 2 3
12 2 3
12 2 3
12 2 3
12 2 3
12 2 3
12 2 3

---------- Post updated at 14:19 ---------- Previous update was at 14:13 ----------

Or

awk '{print $0, T}  NR==2 {sub ($1 FS, ""); T=$0} ' file
1 Like

Hello RudiC,

Little modification to your code as above will not copy fields from line 2nd to last line.

awk 'NR==1 {split ($0, T); MX=NF} NR>=2 {for (i=2; i<=MX; i++) $i=T} 1' Input_file

Thanks,
R. Singh

1 Like

Thank you so much guys. You guys are awesome. I am very new to this forum and i would like to learn alot from you all. :b::b:

You are welcome Dinesh, trust me this is one of the BEST forums I have seen till date for learning UNIX and related stuff.
You are very much welcome to join the learning camp. Enjoy learning :b:

Thanks,
R. Singh
"Where there is a SHELL there is a way."

1 Like

I don't understand - applying your proposal to the sample file yields

# # #
12 # #
12 # #
12 # #
12 # #
12 # #
12 # #
12 # #
12 # #

which doesn't seem to be the desired output.

Hello RudiC,

I am sorry for confusion, seems user has shown line ### before input files, which I didn't put in input files during code creation and you have considered in your code

But both codes seems to be working without that line and with that line too.

Thanks,
R. Singh

1 Like