0

I have 3000 files in c:\data\, and I need to replace a static string in each of them with the name of the file. For example, in the file 12345678.txt there will be some records along with the string 99999999, and I want to replace 99999999 with the filename 12345678.

How can I do this using a batch script?

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175

2 Answers2

3

try this,

replace_string="99999999"
for f in *.txt; do
    sed -i "s/${replace_string}/${f%.*}/g" "$f";
done

Explanation:

  • for f in *.txt; do ... done: Loop through files named *.txt in current directory.
  • sed -i ... file Edit file in place (-i).
  • "s/pattern/replacement/g" Substitutes (s) pattern with replacement globally (g).
  • ${f%.*} Filename without extension (via)
pLumo
  • 397
  • 1
  • 13
0

With GNU tools:

find . -regex '.*/[0-9]+\.txt' -type f -exec gawk -i inplace '
  BEGINFILE {f = FILENAME; sub(".*/", "", f); sub(/\..*/, "", f)}
  {gsub(/\<99999999\>/, f); print}' {} +
Stephane Chazelas
  • 5,859
  • 2
  • 34
  • 31