Sed 收集文件开头的数字

Sed 收集文件开头的数字,sed,awk,grep,Sed,Awk,Grep,我有一个文本文件,其中包含一些数字,例如 There are 60 nuts and 35 apples, but only 24 pears. 我想在相同的文件的开头收集这些数字(60、35、24),特别是在处理后,我想读取文件 read "60" read "35" read "24" There are 60 nuts and 35 apples, but only 24 pears. 我如何使用*nix中提供的一种文本操纵收费来实现这一点?一种方法是: egrep -o [0-9]

我有一个文本文件,其中包含一些数字,例如

There are 60 nuts and 35 apples,
but only 24 pears.
我想在相同的文件的开头收集这些数字(60、35、24),特别是在处理后,我想读取文件

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

There are 60 nuts and 35 apples,
but only 24 pears.
我如何使用*nix中提供的一种文本操纵收费来实现这一点?

一种方法是:

egrep -o [0-9]+ input | sed -re 's/([0-9]+)/read "\1"/' > /tmp/foo
cat input >> /tmp/foo 
mv /tmp/foo input

您可以编写ed会话脚本以就地编辑文件:

{ 
  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
更简洁地说:

printf "%s\n" 0a "$(grep -o '[0-9]\+' nums.txt|sed 's/.*/read "&"/')" "" . w q | ed nums.txt

谢谢glenn,看到老“ed”能在这里干得这么好真是太好了。嗨,glenn,很抱歉打扰你,也许你能帮我一下