2

I have a text file which contains some numerals, for example,

There are 60 nuts and 35 apples,
but only 24 pears.

I want to collect these numerals (60, 35, 24) at the beginning of the same file, in particular, I want after processing, the file to read

read "60"
read "35"
read "24"

There are 60 nuts and 35 apples,
but only 24 pears.

How could I do this using one of the text manipulating tolls available in *nix?

day
  • 2,292
  • 1
  • 20
  • 23

2 Answers2

2

You can script an ed session to edit the file in place:

{ 
  echo 0a    # insert text at the beginning of the file
  grep -o '[0-9]\+' nums.txt | sed 's/.*/read "&"/'
  echo ""
  echo .     # end insert mode
  echo w     # save
  echo q     # quit
} | ed nums.txt

More succinctly:

printf "%s\n" 0a "$(grep -o '[0-9]\+' nums.txt|sed 's/.*/read "&"/')" "" . w q | ed nums.txt
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Thanks glenn, it's amazing to see how the old `ed' could do such a good job in place. – day Jun 03 '11 at 15:28
  • Hi, glenn, sorry to bother, maybe you could help me with http://stackoverflow.com/questions/6236335/for-loop-in-makefile-has-no-effect – day Jun 05 '11 at 06:05
1

One way to do it is:

egrep -o [0-9]+ input | sed -re 's/([0-9]+)/read "\1"/' > /tmp/foo
cat input >> /tmp/foo 
mv /tmp/foo input
codaddict
  • 445,704
  • 82
  • 492
  • 529