fivelements
fivelements

Reputation: 1527

Bash string replacement with regex repetition

I have a file: filename_20130214_suffix.csv I'd like replace the yyyymmdd part in bash. Here is what I intend to do:

file=`ls -t /path/filename_* | head -1`
file2=${file/20130214/20130215}
#this will not work
#file2=${file/[0-9]{8}/20130215/}

Upvotes: 2

Views: 5328

Answers (2)

Jims
Jims

Reputation: 68

[[ $file =~ ^([^_]+_)[0-9]{8}(_.*) ]] && file2="${BASH_REMATCH[1]}20130215${BASH_REMATCH[2]}"

Upvotes: 1

chepner
chepner

Reputation: 531868

The problem is that parameter expansion does not use regular expressions, but patterns or globs(compare the difference between the regular expression "filename_..csv" and the glob "filename_.csv"). Globs cannot match a fixed number of a specific string.

However, you can enable extended patterns in bash, which should be close enough to what you want.

shopt -s extglob    # Turn on extended pattern support
file2=${file/+([0-9])/20130215}

You can't match exactly 8 digts, but the +(...) lets you match one or more of the pattern inside the parentheses, which should be sufficient for your use case.

Since all you want to do in this case is replace everything between the _ characters, you could also simply use

file2=${file/_*_/_20130215_}

Upvotes: 5

Related Questions