Home > Enterprise >  How to replace an unknown string in multiple files under Linux?
How to replace an unknown string in multiple files under Linux?

Time:05-06

I want to change multiple different strings across all files in a folder to one new string.

When the string in the text files (within a same directory) is like this:

  • file1.json: "url/1.png"
  • file2.json: "url/2.png"
  • file3.json: "url/3.png"
  • etc.

I would need to point them all to a single PNG, i.e., "url/static.png", so all three files have the same URL inside pointing to the same PNG.

How can I do that?

CodePudding user response:

you can use the command find and sed for this. make sure you are in the folder that you want to replace files.

find . -name '*.*' -print|xargs sed -i "s/\"url\/1.png\"/\"url\/static.png\"/g"

CodePudding user response:

Suggesting bash script:

#!/bin/bash
# for each file with extension .json in current directory
for currFile in *.json; do
  # extract files ordinal from from current filename
  filesOrdinal=$(echo "@currFile"| grep -o "[[:digit:]]\ ")
  # use files ordinal to identify string and replace it in current file
  sed -i -r 's|url/'"$filesOrdinal".png'|url/static.png|' $currFile
done
  • Related