I have file C1.log which has the following:


I need to find the last / of every line, and then print the next two characters.

For example, my output should be:

  • 3
    This is a work order, not a question. Isn't any demonstrated effort required? – Peter Mortensen Jan 25 at 10:46

With grep that supports PCRE:

grep -oP '.*/\K.{0,2}' infile
  • This \K assertion is used to ignore everything matched before itself
  • .{0,2} matches zero or maximum two characters after last /

For the input below:


The output would be:

  • Shouldn't '/' be escaped? e.g., grep -oP '.*\/\K.{0,2}' infile – Paulo Tomé Jan 24 at 17:34
  • An unescaped forward slash may cause issues if copying/pasting this expression into code. Saw this at RegExr. – Paulo Tomé Jan 24 at 17:50
  • no, / has no special meaning in grep. – αғsнιη Jan 24 at 18:06
  • 1
    @PauloTomé there because it uses for replacement, and since default delimiter is / so it needs to be escaped, or change the delimiter to something else different from / then no need to be escaped, see regex101.com/r/jR55PC/2 I have changed delimiter to @. however as I said / has no special meaning in grep to worry about escaping it. – αғsнιη Jan 24 at 18:36
  • 1
    Thank you for your explanation. – Paulo Tomé Jan 24 at 18:41

Using awk:

awk -F/ '{print substr($NF,1,2)}' C1.log

This uses / as a field separator and then prints two characters from the last field starting at character 1.

  • Thank you. It's working. – Moses Jan 24 at 15:38
  • 2
    If you found the answer useful, please consider accepting it (by clicking on the currently greyed-out checkmark below the vote counter) so that others facing a similar problem may find it more easily. – AdminBee Jan 24 at 15:39

Using sed greedy matching and back references:

$ sed -E 's/(^.*\/)(..)(.*$)/\2/' C1.log
  • But you don’t need to capture the substrings that you aren’t using: sed -E 's/^.*\/(..).*$/\1/'. – Scott Jan 26 at 0:30
  • @Scott. Indeed that is true. – fpmurphy Jan 26 at 6:33

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.