Reputation: 860
I'm using sed to store a string in a variable. I'd like to pick out part of one line in a text file, but am unable to do so.
For example, if a line of text from which I'd like to extract the text is:
{foo bar 1.1.2} foo
And I'd like to extract bar 1.1.2
My command looks like:
BarVersion=$(sed -n "/bar [.0-9]/p" file.txt)
However, if I then write:
echo $BarVersion
I find that the sed command has saved the whole line in BarVersion, not the just the part I was looknig for. i.e. I get {foo bar 1.1.2} foo
Upvotes: 0
Views: 208
Reputation: 60443
If you're running GNU/something,
sed -nr '/^\{([^ ]*) ([^}]*)\} \1$/ s//\2/p'
If the matching 'foo's isn't a requirement it's
sed -n /^{[^ ]* \([^}]*\)} .*/ s//\1/p'
Upvotes: 0
Reputation: 3333
You can do it with grep like this:
BarVersion=$(grep -o "bar [.0-9]*" file.txt)
This seems to work for me, but of course it's not using sed, but in my opinion it's a bit simpler.
-o
means only output the part of the line that matched.
Upvotes: 1
Reputation:
$ echo '{foo bar 1.1.2} foo' | sed -n 's/^.*\(bar [\.0-9]*\)}.*$/\1/p'
bar 1.1.2
s/x/y/
substitutes x
with y
\(\)
forms a group which you can reference via \1
[\.0-9]*
is any number of dots .
and digits^
is the start of the buffer, $
is the end.*
is any number of charactersUpvotes: 2