user1999315
user1999315

Reputation: 31

Shell scripting sub string extraction

I have a set of file names following some pattern. I need to insert a date into the filename string. Now, I also have some files following a slightly different pattern. I would like to know how can a single string match both the requirements.

eg. filenames are like:

abcTrade_proj.dat 
abcPosition_proj.dat 
abcAccount_proj.dat

I'm using below string to construnct the filename like abcTrade_yyyymmdd_proj.dat

${filename%_*}_${DATE}_${filename#*_}

Now, apart from the above file patterns, I have the pattern:

abc_pqr_Account_proj.dat 
abc_pqr_Trade_proj.dat

All i need to do is cut the string till the last _, insert the date and append the string that is there after _, for both the type of file patterns.

Is there any solution for both situations?

Upvotes: 0

Views: 54

Answers (1)

ebo
ebo

Reputation: 2747

If possible, you could use sed to construct the new name as follows:

DATE=$(date +%Y%m%d)
echo "abcTrade_pqr_proj.dat" | sed "s/^\(.*\)_\([^_]*\)/\1_${DATE}_\2/g" 

which results in:

abcTrade_pqr_20140101_proj.dat

Upvotes: 1

Related Questions