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
  •  | 
  •  

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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top