bash 替换所有文件中的字符串 - Unix

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15230865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:45:04  来源:igfitidea点击:

Replace a string in all files - Unix

bashfileunixterminalreplace

提问by alvas

I am trying to replace a string :::with ::for all lines in a batch of txtfiles (it can be considered as a word since there's always a space in front and behind it.

我试图替换字符串:::::批处理中txtfiles的所有线路(也可以,因为总是有一个在前面和后面的空间被认为是一个单词。

I can do it with python like below, but is there a less 'over-kill' / convoluted way of doing this through the unix terminal?(Many pipes allowed)

我可以像下面这样使用 python 来完成,但是通过 unix 终端是否有更少的“过度杀伤”/复杂的方式来做到这一点?(允许多管)

indir = "./td/"
outdir =  './od/'
for infile in glob.glob(os.path.join(indir,"*")):
  _,FILENAME = os.path.split()
  for l in codecs.open(infile,'r','utf8').readlines():
    l = l.replace(":::","::").strip()
    outfile = codecs.open(os.path.join(outdir,FILENAME),'a+','utf8')
    print>>outfile, l

Then i move all files from od to td mv ./od/* ./td/*

然后我将所有文件从 od 移动到 td mv ./od/* ./td/*

回答by Beta

find . -name "./td/*.c" -exec sed -i "s/:::/::/g" '{}' \;

No need for od/at all.

od/根本不需要。

EDIT:

编辑:

A slightly simpler variation:

一个稍微简单的变体:

ls td/*.c | xargs sed -i '' "s/:::/::/g"

回答by chepner

A simple loop to process each file with sedshould suffice.

一个简单的循环来处理每个文件sed就足够了。

for inp in ./td/*; do
    fname=${inp##*/}
    sed 's/:::/::/g' "$inp" > ./od/"$fname"
done