0

https://www.gnu.org/software/sed/manual/sed.html#Command_002dLine-Options

-n
--quiet
--silent
-e script
--expression=script Add the commands in script to the set of commands to be run while processing the input.

https://stackoverflow.com/questions/14593320/insert-field-separator-to-arrange-and-capture-value-in-variable-in-shell-script/14593411#14593411

like this answer:

echo $'For example:\nThis is counter1 1000\nthis counter2 2000\n
     this counter3 is higher value 3000\ndone.\n' |
  sed -ne 's/^.* \([0-9]\{1,99\}\)/\1/p'

I understand ([0-9]\{1,99\}\) refer to pattern integer.
^refer to beginning of a the string.
.* refer to 1 or more character.

But overall, I am still confused with sed -ne 's/^.* \([0-9]\{1,99\}\)/\1/p'

2

1 Answer 1

1

(First, this is not a bash integer regex pattern. sed is handling the regex and has nothing to do with bash)

So I understand that you are unable to figure out the regex in sed -ne 's/^.* \([0-9]\{1,99\}\)/\1/p'

Let's make it simpler. The equivalent code would be sed -E -ne 's/^.* ([0-9]{1,99})/\1/p'

The -E enables extended (modern) regex and you won't have to escape stuff using \

The s/pattern/replacement/ operator looks for a string matching the regex pattern in the left side and replaces it with the string on the right.

Now, let's focus on /^.* ([0-9]{1,99})/

  • ^ matches at the beginning of the line
  • .* matches any character 0 or more times
  • (space) matches a single space character
  • [0-9]{1,99} matches any digits occurring a minimum of 1 time to a max of 99; so any number with a length of 1 to 99

([0-9]{1,99}) is in parentheses which means sed will "capture" this substring and use it in the replacement part where \1 was used.

4
  • Note that it's functionally equivalent to sed -ne 's/^.* \([0-9]\)/\1/p'. The interval operator serves no purpose here as there's nothing that needs to be found after that sequence of digits. [0-9]{1,99} would also match on the first 99 digits of a 300 digit number. It would make a difference in sed -ne 's/^.* \([0-9]\{1,99\}\)$/\1/p' for instance where the $ matches on the end of the subject. Jan 9 at 9:18
  • I understand s/pattern/replacement/ but what does the last character p refer to?
    – Mark
    Jan 9 at 15:36
  • p is a sed directive meaning print whatever was matched.
    – GMaster
    Jan 9 at 15:46
  • @StéphaneChazelas: But yur expression only matches one digit. Jan 9 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.