Tuesday, November 4, 2014

How do you delete specific files older than 7 days in a directory?

foreach my $dir (@ARGV) {
foreach my $file ( grep { (-M) > 7 } glob("$dir/*.{log,zip}") ) {
print "\nRemoving - $file ...";
unlink $file;
}
}

Note:
It deletes all log/zip files in a directory.

Monday, November 3, 2014

How do you get the delimiter used in CSV file in Perl?

use Text::CSV::Separator qw(get_separator);

my $csv_file = "Test01.csv";

my $delimiter = get_separator( path => "$csv_file",
                                   lucky   => 1,
                                   exclude => [':', ' ', '-'],
                                 );

Monday, October 13, 2014

Create predefined folder & sub-folders on Windows.

@echo off

set PWD=%cd%
set dlist=CLASS01 CLASS02 CLASS03
set slist=PHY CHE BIO GEO MATH

for %%i in ( %dlist% ) do (
   if not exist %PWD%\%%i ( mkdir %PWD%\%%i )
   for %%j in ( %slist% ) do (
       if not exist %PWD%\%%i\%%j ( mkdir %PWD%\%%i\%%j )
   )
)

Rename multi files in a folder on Windows.

@echo off

set count=1
set basedir=C:\old_data\report
for /f "tokens=*" %%G in ('dir /a-d /b %basedir%') do (call :subroutine %%G)
goto :eof

:subroutine
for /F "delims=_" %%a in ("%1") do (
   ren "%basedir%\%1" "%%a_SPRW_Light_%count%.txt"
)
set /a count+=1
goto :eof

Example:
"20141013_Test_Rept.dat" will be renamed to "20141013_SPRW_Light_1.txt"

Write colorful text on console in Perl on Windows.

use Win32::Console;

# get current console attributes
my $console = Win32::Console->new(STD_OUTPUT_HANDLE);
my $cons_attrib = $console->Attr();

$console->Attr($FG_LIGHTGREEN | $BG_BLACK);
print "Hi, Welcome to Arabian Nights";
$console->Attr($cons_attrib); #Restore original attributes

Thursday, September 18, 2014

How do you get timestamp in batch file?

@echo off
set timestamp=%date:~-4%-%date:~4,2%-%date:~7,2%:%time:~0,2%-%time:~3,2%-%time:~6,2%
echo %timestamp%

Friday, August 22, 2014

How do you execute PostgreSQL scripts whose names start with 'p_'?

my $path = 'C:\TestSQL';

my @scripts = `dir /B /s $path`;

foreach my $psqlfile (@scripts) {
   if ( $psqlfile =~ /^(.+\\p\_[^\\]+\.sql)\s*$/i ) {
        `psql -q -h <Hostname> -p <Port> -d <Database> -U <Username> -f $psqlfile.sql -o outputfile`;
   }
}

How do you execute all sql files in a directory?

my $path = 'C:\TestSQL';

my @scripts = `dir /B /s $path`;

foreach my $sqlfile (@scripts) {
   if ( $sqlfile =~ /^(.+\.sql)\s*$/i ) {
       `mysql <db_name> -u <user_name> -p <password> < $sqlfile.sql`;
   }
}

Wednesday, August 20, 2014

How do you add path of perl to environment variable on command prompt?

1. Open "cmd.exe" with Administrator Privilege (on right click on app) and type the command below.
     setx path "%path%;C:\Perl64\bin;"
2. Restart "cmd.exe".