0

I've loaded some strings into variable "result". The strings look like this:

school/proj_1/file1.txt
school/proj_1/file2.txt
school/proj_1/file3.txt

I try to get only the name after the last slash, so file1.txt, file2.txt and file3.txt is the desirable result for me. I use this piece of code

for i in $result
do
  grep "school/proj_1/(.*)" $i
done

but it doesn't work. I feel that the regex would work for Python with the caputuring group I created, but I can't really wrap my head around how to use capturing groups in bash or if it is even possible at all.

I'm sorry if it's a dumb question, I'm very new to scripting in bash.

1
  • With grep, if you don't pass the -E flag, you will need to escape any characters that would have a special regex meaning. So I think either grep -E "school/proj_1/(.*)" $i or grep "school/proj_1/\(.*\)" $i should work.
    – 0x5453
    Commented Mar 7, 2018 at 14:02

2 Answers 2

2

You may use a simple approach with a string manipulation operation:

echo "${i##*/}"

${string##substring}
  Deletes longest match of $substring from front of $string.

Or using a regex in Bash, you may get the capturing groups like

result=("school/proj_1/file1.txt" "school/proj_1/file2.txt" "school/proj_1/file3.txt")
rx='school/proj_1/(.*)'
for i in "${result[@]}"; do
    if [[ "$i" =~ $rx ]]; then
        echo "${BASH_REMATCH[1]}"
    fi
done

See the online demo. Here, ${BASH_REMATCH[1]} is the contents inside capturing group #1.

2

Try this :

variable declaration :

$ result="school/proj_1/file1.txt
school/proj_1/file2.txt
school/proj_1/file3.txt"

Commands :

(all as one-liners)

$ grep -oP "school/proj_1/\K.*" "$i" <<< "$result"

or

$ awk -F'/' '{print $NF}' <<< "$result 

or

$ sed 's|.*/||' <<< "$result"

or if number of sub dirs are fixed :

$ cut -d'/' -f3 <<< "$result"

Output :

file1.txt
file2.txt
file3.txt

Not the answer you're looking for? Browse other questions tagged or ask your own question.