Search code examples
stringbashsedtxt

Fetch the txt file name for each path in a string


I'm trying to extract the txt file names in directory my-repo/text/*/<file_name>.txt by using the following in bash
echo "my-repo/text/level1_dir/der.txt my-repo/scripts/af.py my-repo/text/level1_dir/another/er_abc.txt my-repo/text/deep/nested/my-file.txt" | sed -E 's|my-repo/text/.*/([^/]+)\.txt|\1|g'

but I get the following output : my-file, whereas the output I need is der er_abc my-file.

Is there a way to do this?


Solution

  • You can use this tr | sed solution:

    echo "my-repo/text/level1_dir/der.txt my-repo/scripts/af.py my-repo/text/level1_dir/another/er_abc.txt my-repo/text/deep/nested/my-file.txt" |
    tr ' ' '\n' |
    sed -E '/\.txt$/!d; s|my-repo/text/[^ ]+/([^/.]+)\.txt|\1|g'
    
    der
    er_abc
    my-file