I'm looking for a batch script that appends the names of multiple text files to the first line of each file

StackOverflow https://stackoverflow.com/questions/21210066

Question

I have a folder that contains more than 200 text file (.txt)

I want an easy way to add each file name to the first line of each file.

example I have a file called "I am a file.txt" with the following content:

"
I am line one
I am line two
"

this should become something like this:

"
I am a file
=====
I am line one
I am line two
"

I'm wondering if someone could help me build a batch script that does that.

the reason for that is I want to upload all my text files to Evernote. But Evernote doesn't read the file name, instead it name the note as the first line in the text.

Was it helpful?

Solution

That worked for me:

(just past this in a file called whatever.bat and run it)

@echo off
for /f "eol=: delims=" %%F IN ('dir /b /s "C:\Users\MyPC\Desktop\myDir\*.txt"') do (
  (
    echo %%~nF
    echo ___________________________
    type "%%F"
  )>"%%F.new"
  move /y "%%F.new" "%%F"
)

pause

OTHER TIPS

@echo off
pushd "pathToYourFolder"
for /f "eol=: delims=" %%F in ('dir /b /a-d *.txt') do (
  (
    echo %%F
    echo =====
    type "%%F"
  )>"%%F.new"
  move /y "%%F.new" "%%F"
)

Assuming the filenames are passed as arguments to the script, you could use this:

#!/bin/bash

for file in "$@"
do
   sed -i "1 i ${file%.*}\n=====" "$file"
done

Assuming of course you have sed available, but since you have tagged the question with bash I imagine you have Cygwin installed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top