stringbashsubstitution

Bash string substitution - bug?


I am trying to do some file management in bash and I have strings in this format:

1 dir/hello.txt
2 dir2/bar.jpg

When I run this substitution: ${FOO/[:space:]*/Hello} I get this result: 1 dir/hHello

The goal is to substitute everything after the first space (including the space) with Hello

Seems like a bug to me. In such a case, please confirm and I will take the issue upstream.


Solution

  • You almost had it right. From your quote:

    Within [ and ], character classes can be specified using the syntax [:class:], where class is one of the following classes defined in the POSIX standard: [...]

    So, you need to double up on the square brackets:

    s='1 dir/hello.txt'
    echo "${s/[[:space:]]*/Hello}"
    

    produces 1Hello.