用文件名替换文件中的静态字符串的批处理脚本 [英] Batch script that replaces static string in file with filename

查看:111
本文介绍了用文件名替换文件中的静态字符串的批处理脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c:\data\中有3000个文件,我需要用文件名替换每个文件中的静态字符串.例如,在文件12345678.txt中将有一些记录以及字符串99999999,我想用文件名12345678替换99999999.

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?

推荐答案

尝试一下,

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

说明:

  • for f in *.txt; do ... done:循环浏览当前目录中名为*.txt的文件.
  • sed -i ... file就地编辑file (-i).
  • "s/pattern/replacement/g"替换(s)模式,并在全局范围内(g)替换 .
  • ${f%.*}不带扩展名的文件名(通过)
  • 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)

这篇关于用文件名替换文件中的静态字符串的批处理脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆