-2

I need to get text that includes alphabetic characters and _ from this format of file name: oracle_NAME_OF_DB_USER.log , so PARAM=NAME_OF_DB_USER. Couldn't find the best regex to use in a for loop:

LIST=oracle_*.log

for file in $LIST; do
.
.
.
USER=${extracted_file_name}
2
  • is the file of pattern oracle_<username>.log ? Commented Nov 21, 2018 at 10:25
  • @stack0114106 yes Commented Nov 21, 2018 at 10:32

3 Answers 3

2

Here is a pure BASH answer:

for file in oracle_ABC_USER_1.log oracle_ABC_USER_2.log oracle_ABC_USER_ADMIN_1.log oracle_ABC_USER_ADMIN_2.log oracle_NAME_OF_DB_USER.log; do
    [[ $file =~ oracle_(.*)[.]log ]]
    echo ${BASH_REMATCH[1]}
done

And here is the output of the commands above:

ABC_USER_1
ABC_USER_2
ABC_USER_ADMIN_1
ABC_USER_ADMIN_2
NAME_OF_DB_USER
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @accdias BASH_REMATCH is new to me, happy to discover it now :)
You're welcome. :-)
0

Assuming that you have a set of files like below

> ls -1 oracle*
oracle_ABC_USER_1.log
oracle_ABC_USER_2.log
oracle_ABC_USER_ADMIN_1.log
oracle_ABC_USER_ADMIN_2.log
oracle_NAME_OF_DB_USER.log

The below perl command should get you the names that you are expecting

> perl -ne ' BEGIN { @files=glob("oracle*.log"); foreach (@files) {s/^oracle_(.*)\.log/_\1/g; print "$_\n"} exit } '
_ABC_USER_1
_ABC_USER_2
_ABC_USER_ADMIN_1
_ABC_USER_ADMIN_2
_NAME_OF_DB_USER
> 

Does this help?.

More compact one:

> perl -ne ' BEGIN { s/^oracle_(.*)\.log/_\1/g and print "$_\n" for glob("oracle*.log"); exit}'
_ABC_USER_1
_ABC_USER_2
_ABC_USER_ADMIN_1
_ABC_USER_ADMIN_2
_NAME_OF_DB_USER
> 

Comments

0

What about this:

<Prompt>:/C/Temp_Folder/tralala$ ls -ltra
total 0
drwxrwxrwx 1 Username Groupname 512 Nov 21 11:43 ..
-rwxrwxrwx 1 Username Groupname   0 Nov 21 11:44 oracle_ABC.log
-rwxrwxrwx 1 Username Groupname   0 Nov 21 11:44 oracle_123.log
-rwxrwxrwx 1 Username Groupname   0 Nov 21 11:44 oracle_ABC_123.log
-rwxrwxrwx 1 Username Groupname   0 Nov 21 11:44 something_else.log
drwxrwxrwx 1 Username Groupname 512 Nov 21 11:48 .
<Prompt>:/C/Temp_Folder/tralala$ ls -ltra | grep "oracle[_A-Za-z0-9]*.log"
-rwxrwxrwx 1 Username Groupname   0 Nov 21 11:44 oracle_ABC.log
-rwxrwxrwx 1 Username Groupname   0 Nov 21 11:44 oracle_123.log
-rwxrwxrwx 1 Username Groupname   0 Nov 21 11:44 oracle_ABC_123.log

The regular expression oracle[_A-Za-z0-9]*.log mentions all characters, small letters and capitals, digits and underscore.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.