Find and Replace Only 1st line in many csv files

ttist25
ttist25 used Ask the Experts™
on
Hello,

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:
field1|field2|field3|field4

replace | with "|" so the first row would be:
field1"|"field2"|"field3"|"field4

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.  

Thanks!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Distinguished Expert 2018
Commented:
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:
$file="q.csv"
$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:
https://social.technet.microsoft.com/Forums/en-US/03e89b2f-811a-4453-8168-46502abd402b/powershell-overwrite-a-specific-line?forum=ITCG


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

Author

Commented:
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

Commented:
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