Replace a string in all files - Unix

2019-03-13 16:04发布

问题:

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.

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)

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/*

回答1:

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

No need for od/ at all.

EDIT:

A slightly simpler variation:

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


回答2:

A simple loop to process each file with sed should suffice.

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