views:

95

answers:

3

Greetings!

I have a text file with parameter set as follows:


NameOfParameter Value1 Value2 Value3 ... ...


I want to find needed parameter by its NameOfParameter using regexp pattern and return a selected Value to my Bash script. I tried to do this with grep, but it returns a whole line instead of Value.

Could you help me to find as approach please?

A: 

It was not clear if you want all the values together or only one specific one. In either case, use the power of cut command to cut the columns you want from a file (-f 2- will cut columns 2 and on (so everything except parameter name; -d " " will ensure that the columns are considered to be space-separated as opposed to default tab-separated)

egrep '^NameOfParameter ' your_file | cut -f 2- -d " "
DVK
A: 

Bash:

values=($(grep '^NameofParameter '))
echo ${values[0]}    # NameofParameter 
echo ${values[1]}    # Value1
echo ${values[2]}    # Value2
# etc.

for value in ${values[@:1]}    # iterate over values, skipping NameofParameter
do
    echo "$value"
done
Dennis Williamson
Is there any opportunity to use this method for data with non-space delimiters: comma, dot, tab, etc.?
Andrey Kazak
@Andrey: Set IFS to the delimiter: `saveIFS=$IFS; IFS=','; values=($(grep '^NameofParameter ')); IFS=$saveIFS; ...`
Dennis Williamson
A: 

OK, thank you guys!

Is there any way in Linux to return only and exactly that part of text that mached a regexp?

Andrey Kazak
This should have been posted as a comment or an edit to the question rather than an answer. Please delete it and repost in one of those ways. `grep -o` returns only the matched part.
Dennis Williamson