2

I have CentOS and this bash script:

#!/bin/sh
files=$( ls /vps_backups/site )
counter=0
for i in $files ; do
echo $i | grep -o -P '(?<=-).*(?=.tar)'
let counter=$counter+1
done

In the site folder I have compressed backups with the following names :

    site-081916.tar.gz
    site-082016.tar.gz
    site-082116.tar.gz
    ...

The code above prints : 081916 082016 082116

I want to put each extracted date to a variable so I replaced this line

echo $i | grep -o -P '(?<=-).*(?=.tar)'

with this :

dt=$($i | grep -o -P '(?<=-).*(?=.tar)')
echo $dt

however I get this error :

./test.sh: line 6: site-090316.tar.gz: command not found

Any help please?

Thanks

2 Answers 2

2

you still need the echo inside the $(...):

dt=$(echo $i | grep -o -P '(?<=-).*(?=.tar)')
Sign up to request clarification or add additional context in comments.

2 Comments

Well, that's a fast and perfect answer for my issue, I'm new to bash, thank you.
for what it's worth: you can make this more efficient by moving the grep into the $files definition: files=$( ls /vps_backups/site | grep -o -P '(?<=-).*(?=.tar)' ) - that way, files will be just the filename parts you're looking for already.
1

Don't use ls in a script. Use a shell pattern instead. Also, you don't need to use grep; bash has a built-in regular expression operator.

#!/bin/bash
files=$( /vps_backups/site/* )
counter=0
for i in "${files[@]#/vps_backups/site/}" ; do
  [[ $i =~ -(.*).tar.gz ]] && dt=${BASH_REMATCH[1]}
  counter=$((counter + 1))
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.