Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract using sed or grep

I am fairly new to grep and sed commands.How can +50.0 be extracted from Core 0: +50.0°C (high = +80.0°C, crit = +90.0°C) using grep or sed in bash script?

acpitz-virtual-0
Adapter: Virtual device
temp1:        +50.0°C  (crit = +89.0°C)
temp2:        +50.0°C  (crit = +89.0°C)

coretemp-isa-0000
Adapter: ISA adapter
Core 0:       +50.0°C  (high = +80.0°C, crit = +90.0°C)
Core 2:       +47.0°C  (high = +80.0°C, crit = +90.0°C)

Bash Script:

#!/bin/bash

temp=`sed -n '/^Core 0:      $/,/^(high/p' ~/Desktop/sensors.txt`

echo $temp
like image 858
curious_coder Avatar asked Sep 05 '13 17:09

curious_coder


People also ask

What is the difference between sed and grep?

The sed command is a stream editor that works on streams of characters. It's a more powerful tool than grep as it offers more options for text processing purposes, including the substitute command, which sed is most commonly known for.

What is the use of grep and sed?

This collection of sed and grep use cases might help you better understand how these commands can be used in Linux. Tools like sed (stream editor) and grep (global regular expression print) are powerful ways to save time and make your work faster.

How do I extract text between two words in Unix?

How do I extract text between two words ( <PRE> and </PRE> ) in unix or linux using grep command? Let us see how use the grep command or egrep command to extract data between two words or strings. I also suggest exploring sed/awk/perl commands to extract text between two words on your Linux or Unix machine.


2 Answers

Using grep -oP (PCRE regex):

grep -oP 'Core 0: +\K[+-]\d+\.\d+' ~/Desktop/sensors.txt
+50.0
like image 87
anubhava Avatar answered Oct 06 '22 01:10

anubhava


grep -e '^Core 0:' [input] | awk '{ print $3 }'

Or alternately, just in awk,

awk '{ r = "^Core 0:" } { if(match($0,r)) { print $3 } }' [input]

Both of these will print the field you seem to be looking for, with the surrounding whitespace eliminated.

like image 42
qaphla Avatar answered Oct 06 '22 01:10

qaphla