2

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

4
  • 1
    Why use sed for this? With awk you could simply do awk -vk="$var" '$2==k{print $1}' file Commented Nov 8, 2016 at 19:53
  • Expected Output is the Number saved in abc. Commented Nov 8, 2016 at 19:54
  • @user000001 can you explain "-vk" and the "k" before the print? Commented Nov 8, 2016 at 19:56
  • @Thunfisch: Sure, I 'll add an answer Commented Nov 8, 2016 at 19:56

3 Answers 3

3

many problems here:

  • there are spaces, you don't account for them
  • the ^ must be inside the char class to make a negative letter
  • you're using -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 
Sign up to request clarification or add additional context in comments.

Comments

2

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}.

Comments

1

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 spaces
  • Y-[OH]2*: search for Y- string followed by N or H with optional 2
  • \1/p: captured string \1 is output with p command

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.