Link to home
Start Free TrialLog in
Avatar of xbox360dp
xbox360dp

asked on

How to delete rows in a file based on the file name.

Gurus,

I have a request to delete rows in a file based on the file name.

Example
File name: SMC_ELEMENTTest_ITEM_123_201_59_Base.txt

Before:
XXX|123|Red
XXX|456|Blue
XXX|123|Black

After:
XXX|123|Red
XXX|123|Black

Example
File name: SMC_ELEMENTTest_ITEM_456_201_59_Base.txt

Before:
XXX|123|Red
XXX|456|Blue
XXX|123|Black

After:
XXX|456|Blue


The file name is basically the same except for the number I put in bold.

What is the best way to accomplish this task?
Avatar of aikimark
aikimark
Flag of United States of America image

Is Perl your tool of choice or the only tool at your disposal?
Avatar of Bill Prew
Bill Prew

Not sure if you are even working in Windows, but here is a basic BAT script that could do the job.  Save as a BAT and then run as follows:

EE28699979.bat SMC_ELEMENTTest_ITEM_123_201_59_Base.txt SMC_ELEMENTTest_ITEM_123_201_59_Base.out

See if that does what you want.

If you really want to replace the single input file with the new output we can add some logic to the script to cover that, but for a first test I kept it simple in case you were wanting a different OS or script language (like Perl).

@echo off
setlocal

if "%~1" EQU "" (
  echo Missing input file name.
  exit /b
)

if "%~2" EQU "" (
  echo Missing output file name.
  exit /b
)

for /f "tokens=4 delims=_" %%A in ("%~n1") do (
  find /i "|%%A|" <%~1 >%~2
)

Open in new window

~bp
Using Powershell:
create a folder called c:\temp\FileNums and copy few of your files in that folder and follow the steps to test.
Save the following as Processfiles.ps1 and right click the file and "run with Powershell"
$files = Get-ChildItem C:\temp\FileNums -Filter *.txt

foreach ($file in $files)
{
$num = $($file.name)[21..23] -join ''
$newcontent = Get-Content $($file.Fullname) | Select-String $num  
$newcontent | out-file $($file.Fullname) -Force

}

Open in new window

Avatar of xbox360dp

ASKER

Hi All,

Perl is the language of choice and I'm in a Linux environment.

Thanks!
ASKER CERTIFIED SOLUTION
Avatar of wilcoxon
wilcoxon
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial