Hello everybody,
I have a file like this : "window 1 truck 3 duck 2... fire 1... etc..." and I would like to print the following number of a word I am searching for. (For example here, if I search for the word "fire", I will print "1")
Thank you for your help !
sed 's/.* fire \([0-9][0-9]*\) .*/\1/' file
s="window 1 truck 3 duck 2... fire 1"
f=0
for i in $s;
do
if [ $f -eq 1 ];then
echo "Found number $i"
fi
case $i in
fire) f=1 ; continue;;
esac;
done
Doesn't work here:
$ uname -a
SunOS db012a 5.8 Generic_117350-35 sun4us sparc FJSV,GPUZC-M
$ which sed
/usr/bin/sed
$ cat file
window 1 truck 3 duck 2 fire 1
$ sed 's/.* fire \([0-9][0-9]*\) .*/\1/' file
window 1 truck 3 duck 2 fire 1
This is because in your sample file, after the "1", there is no space.
The sed statement has a <space> after the \) bracket. It should be
# sed 's/.* fire \([0-9][0-9]*\).*/\1/' file
1
for your case of sample file
Then lets do this:
sed 's/ *.*fire \([0-9][0-9]*\).*/\1/' file
Works with/without leading/trailing spaces.
But the above pattern will also catch words like backfire, spitfire etc...
Thanks for pointing that out. This should lay such issues to rest:
$ cat file
window 0 truck 3 duck 2 spitfire 8 fire 1 backfire 9
$ sed 's/.*\<fire\> \([0-9][0-9]*\).*/\1/' file
1
$ sed 's/.*\<spitfire\> \([0-9][0-9]*\).*/\1/' file
8
$ sed 's/.*\<window\> \([0-9][0-9]*\).*/\1/' file
0
$ sed 's/.*\<backfire\> \([0-9][0-9]*\).*/\1/' file
9