LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   grep filter within line? (https://www.linuxquestions.org/questions/linux-newbie-8/grep-filter-within-line-907379/)

qrange 10-10-2011 08:22 AM

grep filter within line?
 
after using grep, I have the following line:
Code:

:Temperature 49
how to filter it out some more, so that only '49' is left?
thanks.

colucix 10-10-2011 08:34 AM

You can either pipe the output to another grep to match exactly the number at the end of the line and using the -o option to print out only the matching part:
Code:

grep Temperature file | grep -E -o [0-9]+$
To avoid the double grep command, you can use awk (or even sed) to match the Temperature pattern and extract only the information you need:
Code:

awk '/:Temperature/{print $NF}' file

MTK358 10-10-2011 11:44 AM

Or use sed:

Code:

sed 's/^:Temperature \([0-9]\+\)$/\1/'
This will eliminate the need for the first grep command, too.

rng 10-10-2011 12:14 PM

You can also use 'cut' command:

$ echo ":temperature 49" | cut -d" " -f2
49

qrange 10-11-2011 02:32 AM

thanks all.

er, there are actually two lines with :Temperature, and I'd like to merge both numbers into one line.
is there a way to combine these two awk into single awk:

Code:

awk '/:Temperature/{print $2}' | awk '{ printf "%s ", $0 }'
(I plan to use it in cron script and wish to reduce resource usage as much as possible)
or some better way?

colucix 10-11-2011 02:34 AM

Quote:

Originally Posted by qrange (Post 4495265)
er, there are actually two lines with :Temperature, and I'd like to merge both numbers into one line.

Of course. Please show us the two lines and the desired result.

qrange 10-11-2011 02:43 AM

nevermind, I just found out how to do it:
awk '/:Temperature/{printf "%s ", $2}'


the two lines are these:
:Temperature 48
:Temperature 25

and output should be:
48 25


thanks.

colucix 10-11-2011 02:51 AM

That's it. You may want to add a terminating newline:
Code:

awk '/:Temperature/{printf "%d ", $NF} END{printf "\n"}' file


All times are GMT -5. The time now is 10:32 AM.