问题
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
Editfile
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