I'm looking to automate a process whereby a part of the filename is what is used to replace a value inside the file itself.

Currently I use a manual process that looks like this:

get the orgname manually

$ grep -o orgname......... *2017-04* |uniq

Then replace orgname with new name

$ sed -i 's/ABC1234/5678/g' `*`5678`*` ; sed -i 's/DEF2345/6789/g' `*`6789`*`; sed -i etc...

The final result would look like this:


The files are named like this:


Whatever is after orgname= needs to change from ABC5678 to whatever comes after Lxxxx, only in files with the same xxxx in its filename.

I'm having a hard time getting my head around how to extract that number from the file name and using it in a sed. There are hundreds of files (each with their own date) and 6 different number pairs to work with. I'm hoping to write a bash script that does this all at once.

I was trying to use grep -P combined with putting that into some sort of variable and using sed but maybe there is a better/easier way?

Let me know if there are any additional questions.

  • what does mean only in files with the same xxxx in its filename. ? Should it make replacements on multiple files at once? May 8, 2017 at 19:50
  • Yes multiple files. There are several hundred files in the dir that need to be modified.
    – Keith
    May 8, 2017 at 20:40

1 Answer 1


Once the filename is in a variable, you can use a shell parameter expansion operator to extract part of it. Then substitute that into the sed command. Below I use the substring operator to get 4 characters starting from position 20.

for file in rsa.collect.rsa-IB_L*.log.web1.decrypt; do
    sed -i "s/orgname=[^&]*/orgname=$orgname/" "$file"
  • I think I may have found (one possible) solution but yours looks much better than mine. (Can't seem to figure out how to format this...) for l in ls; do FI="$(echo $l |cut -c21-24)" ORG="$(grep -o orgname........ $l | cut -d"=" -f2 | cut -d"&" -f1|uniq)" sed -i 's/$ORG/$FI/g' $l|grep $FI done
    – Keith
    May 8, 2017 at 20:42
  • Thank you for much for this, so much more elegant than my own solution!
    – Keith
    May 8, 2017 at 20:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .