Reputation: 129
Hi i have a file containing the following:
7 Y-N2
8 Y-H
9 Y-O2
I want to match it with the following sed command and get the number at the beginning of the line:
abc=$(sed -n -E "s/([0-9]*)(^[a-zA-Z])($j)/\1/g" file)
$j
is a variable and contains exactly Y-O2
or Y-H
.
The Number is not the linenumber.
The Number is always followed by a Letter.
Before the Number are Whitespaces.
echoing $abc
returns a whiteline.
Thanks
Upvotes: 2
Views: 3772
Reputation: 15461
Try this:
abc=$(sed -n "s/^ *\([0-9]*\) *Y-[OH]2*.*/\1/p" file)
Explanations:
^ *
: in lines starting with any number of spaces\([0-9]*\)
: following number are captured using backreference*
: after any number of spacesY-[OH]2*
: search for Y-
string followed by N
or H
with optional 2
\1/p
: captured string \1
is output with p
commandUpvotes: 1
Reputation: 33307
Sed seems to be overly complex for this task, but with awk you can write:
awk -vk="$var" '$2==k{print $1}' file
With -vk="$var"
we set the awk
variable k
to the value of the $var
shell variable.
Then, we use the 'filter{command}'
syntax, where the filter $2==k
is that the second field is equal to the variable k
. If we have a match, we print the first field with {print $1}
.
Upvotes: 2
Reputation: 140148
many problems here:
^
must be inside the char class to make a negative letter-n
option, so you must use p
command or nothing will ever be printed (and the g
option is useless here)working command (I have changed -E
by -n
because it was unsupported by my sed
version, both should work):
sed -nr "s/ *([0-9]+) +([^a-zA-Z])($j)/\1/p" file
Note: awk
seems more suited for the job. Ex:
awk -v j=$j '$2 == j { print $1 }' file
Upvotes: 3