LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Search pattern and assign to Variable (https://www.linuxquestions.org/questions/linux-newbie-8/search-pattern-and-assign-to-variable-4175433634/)

uk.engr 10-23-2012 02:56 AM

Search pattern and assign to Variable
 
Assalam o Alaikum!

I used this command to search particular pattern from file:

grep -n "em16" abc.txt

--> em16 value1d 234


I want to assign this random value "234" to variable? for every time this value changes, I want to filter out other text and want this random value 234 to be assigned to variable.

thanks!

chrism01 10-23-2012 04:47 AM

If that's exactly one space between the fields, then
Code:

a=$(grep -n "em16" t.t|cut -d' ' -f3)
echo $a
234

For more spaces between each field, use awk
Code:

b=$(grep -n "em16" t.t|awk '{print$3}')
echo $b
234


uk.engr 10-23-2012 05:11 AM

Thanks dear, this helps me to proceed ahead

David the H. 10-23-2012 11:47 AM

There's no need to combine grep and awk (or grep and sed). Just use the one that has the greater flexibility.

Code:

b=$( awk '/em16/ { print $NF }' abc.txt )
b=$( sed -n '/em16/ s/.* //p' abc.txt )

NF in awk represents the final field, no matter what it is. In the sed expression "s/.* //" removes everything up to and including the final space in the line.


All times are GMT -5. The time now is 06:41 PM.