1

I want to create a dynamic string variable that holds file extension from a configuration text file like this. The bad thing is that the string value contains regex expression:

EXCLUDE_EXTENSION="\.(log|txt|png)$"

where the log, txt and png extensions I get it from a text file called excluded_ext.txt. So the content of the excluded_ext.txt is:

log
txt
png

so whenever I add another extension in excluded_ext.txt, I will get an updated extension inside the variable EXCLUDE_EXTENSION. Example if I add an extra extension of 'log' inside excluded_ext.txt

log
txt
png
log

then the value of variable EXCLUDE_EXTENSION should be updated automatically to:

EXCLUDE_EXTENSION="\.(log|txt|png|log)$"

I think I might need to use regex but I'm not sure how to achieve this.

#!/bin/sh
# read from a text file
EXCLUDED_TEXT=`cat excluded_ext.txt`
# create array from the text file
# Im not sure how to go next.

2 Answers 2

3

Using paste and a command substitution:

EXCLUDE_EXTENSION='\.('"$(paste -d'|' -s excluded_ext.txt)"')$'
1
  • never thought about the paste command. tq.
    – Kalib Zen
    Jun 6, 2020 at 7:48
2

If you're using bash (as per your title) rather than sh (as shown in your code snippet), then you should be able to do something like this:

mapfile -t exts < excluded_ext.txt        # this creates the array

OldIFS="$IFS"
IFS='|'
printf -v exclude_extension '\.(%s)$' "${exts[*]}"
IFS="$OldIFS"

echo "$exclude_extension"

"${exts[*]}" expands to the elements of exts, separated by the first character of the current IFS.

1
  • tq so much, i wish to upvote this answer but i have no right.
    – Kalib Zen
    Jun 6, 2020 at 7:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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