Find and Replace Only 1st line in many csv files

ttist25 used Ask the Experts™

I have over 100 CSV files that I need to pre-process before importing to SQL.  The files are too large to open in Excel.

What I'm trying to do is modify the first line (the header row) of each file to add double-quotes to the field terminators.

For example, given this header row:

replace | with "|" so the first row would be:

Notepad++ has a "find in files" feature that can use regex but I'm not sure how to linit it to the first line.

Any ideas would be greatly appreciated.  

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Distinguished Expert 2018
Are you sure you don't want:  "field1"|"field2"|"field3"|"field4"

with double quotes at the start and end?

Since you mention notepad++ I'm guessing Windows?

If so, try Powershell:
$content=Get-Content -Path $file
$content[0] =  '"' + $($content[0] -replace '\|','"|"') + '"'
$content | Set-Content -Path $file
type q.csv

Open in new window

It started with:

If you want as you originally wanted it, just remove the concatenation:
$content[0] =  $content[0] -replace '\|','"|"'


Thanks slightwv -

I ended up installing sed from mingw and ran the following command to get the desired output:

for i in `find . -iname *.csv` ; do  sed -i '1s/|/\"|\"/g' $i ; done

Thanks again for your help!
sed or perl is what I would use to do this.  Glad you solved it on your own.
Most Valuable Expert 2012
Distinguished Expert 2018

You should use the utilities the OS gives you, especially when it is Powershell.  It is incredibly powerful/

If I were already in a Linux environment, sure use seq.  Since you are on Windows, why install Linux tools?

Note:  You can use Wildcards in Powershell go get all the files as well.
I completely disagree with slightwv.  You should use whatever tools work best which are usually unix/linux tools.  I always have Cygwin 64-bit (though mingw is a better option as long as it has the tools you want) and Strawberry Perl installed on Windows machines because they simply work better than what is included with Windows.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial