Why does regex show a match even when one of the characters isn't there in the string?

StackOverflow https://stackoverflow.com/questions/23633202

  •  21-07-2023
  •  | 
  •  

Frage

when running this:

echo "abcd/fgh/ijkl" | sed 's|[^/]*/\(.*\)|\1|'

the output as expected is

fgh/ijkl

but when running this:

echo "abcd" | sed 's|[^/]*/\(.*\)|\1|'

The output is

abcd

instead of the expected null string. Why does this match even when there is no / in the string. Is this due to the greediness of the regex. How do I make it work correctly?

War es hilfreich?

Lösung

It doesn't match. The substition in sed will only run on matching lines, and sed by default prints all lines. Try

echo "abcd" | sed -n 's|[^/]*/\(.*\)|\1|p'

The -n flag means "No output by default" and the p modifier at the end will print whenever it does a substitution.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top