Batch script that replaces static string in file with filename

ぐ巨炮叔叔 提交于 2019-12-13 04:16:07

问题


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?


回答1:


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)



回答2:


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}' {} +


来源:https://stackoverflow.com/questions/52101137/batch-script-that-replaces-static-string-in-file-with-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!