Place variables at the beginning of each line

Hello all,

I am very new to the shell scripting and I hope someone can help me with this.
I have thousands of files with certain format of information and I need to do this for all my files.

For each file, grab the numbers in the first and second rows and place them in the position 1 and 2 of the rest rows.
The numbers of the first and second rows are different for each file and also each file has different number of rows.

Here's the examples:

ptrfghbc 44.23
mkhtwsbhp 234.51
1995 56 26 26358 266665 251 32
1995 65 58 22355 551223 352 25
1996 32 52 55852 255632 335 25

I'd like to have something like this:

ptrfghbc 44.23
mkhtwsbhp 234.51
44.23 234.51 1995 56 26 26358 266665 251 32
44.23 234.51 1995 65 58 22355 551223 352 25
44.23 234.51 1996 32 52 55852 255632 335 25

Your help is much appreciated.

Franklin52's solution below should solve the problem

sed '
  N
  p
  s/.* \(.*\)\n.* \(.*\)/\1 \2/
  :loop
  $d
  N
  s/\n/ /
  p
  s/\( [^ ]*\) .*/\1/
  b loop
 '

Narrative: When the first line is in the buffer, get the second, print both, extract the final fields of both and concatenate to be prefix, create a loop branch target, delete the prefix if there are no more lines, get the next line, turn the linefeed into a space, print it out, remove the suffix and loop.

Another one:

awk '/^[a-z]/{s=s?s FS $2:$2; print; next}{$1=s FS $1}1' file
awk '(NR<3){A[NR]=$2}{print((NR>2)?A[1]" "A[2]" "$0:$0)}' input

or

awk '(NR<3){A[NR]=$2}{print((NR>2)?A[1]FS A[2]FS$0:$0)}' input

or

awk '{A[NR]=$2;print(NR>2)?A[1]FS A[2]FS$0:$0}' input
[root@lyisy22:~/sand]# cat input
ptrfghbc 44.23
mkhtwsbhp 234.51
1995 56 26 26358 266665 251 32
1995 65 58 22355 551223 352 25
1996 32 52 55852 255632 335 25
[root@lyisy22:~/sand]# awk '(NR<3){A[NR]=$2}{print((NR>2)?A[1]" "A[2]" "$0:$0)}' input
ptrfghbc 44.23
mkhtwsbhp 234.51
44.23 234.51 1995 56 26 26358 266665 251 32
44.23 234.51 1995 65 58 22355 551223 352 25
44.23 234.51 1996 32 52 55852 255632 335 25
[root@lyisy22:~/sand]#
1 Like

Thank you so very much everybody.

All the codes suggested by ctsgnb are working flawlessly. Great work!

I tested the two codes by danmero and Franklin52 and nothing is changed in my file. I got no error but it just returned the original file back to me.

I have not tested the code by DGPickett yet. I am a newbie and I need more time to figure out what should I do with these lines! I will surely test it later today.

You guys are awesome. Thanks again!

awk '(NR<3&&p=p (p?FS:x)$2)||$0=p FS$0' file
1 Like

Just send your file through: sed '...' <input >output

Enjoy!

Awk should be better at this, as it has field sense. I just lay out my commands so they are easier to review. White space is almost free, but errors . . . .

1 Like

Nice one :wink: