I am using T-SQL
I have a few excel files located here: C:\\MyFiles\\
I want to remove all the apostrophes in the file names in that directory.<
SET NOCOUNT ON;
CREATE TABLE #FileList
(
FileID INT IDENTITY(1, 1)
,Line VARCHAR(512)
)
CREATE TABLE #temp
(
isFileThere BIT
,isDirectory BIT
,parentDirExists BIT
)
DECLARE @Command VARCHAR(1024)
, @RowCount INT
, @counter INT
, @FileName VARCHAR(1024)
, @FileExists BIT
SET @Command = 'dir C:\MyFiles\ /A-D /B'
PRINT @Command
INSERT #FileList
EXEC master.dbo.xp_cmdshell @Command
DELETE FROM #FileList
WHERE Line IS NULL
SELECT @RowCount = COUNT(*)
FROM [#FileList]
SET @counter = 1
WHILE ( @counter <= @RowCount )
BEGIN
SELECT @FileName = [Line]
FROM [#FileList]
WHERE [FileID] = @counter
SET @Command = 'C:\MyFiles\' + @FileName + ''
PRINT @Command
INSERT [#temp]
EXEC master.dbo.xp_fileExist @Command
SELECT @FileExists = [isFileThere]
FROM [#temp]
IF @FileExists = 1
AND CHARINDEX('''', @FileName) > 0
SET @Command = 'REN "C:\MyFiles\' + @FileName + '" "'
+ REPLACE(@FileName, '''', '') + '"'
ELSE
SET @Command = ''
SET @counter = @counter + 1
PRINT @Command
IF LEN(@Command) > 0
EXEC master.dbo.xp_cmdshell @Command
END
DROP TABLE #FileList
DROP TABLE [#temp]