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
      CommentedJun 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
      CommentedJun 6, 2020 at 7:48

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.