Search code examples
shellcattee

how to read a value from filename and insert/replace it in the file?


I have to run many python script which differ just with one parameter. I name them as runv1.py, runv2.py, runv20.py. I have the original script, say runv1.py. Then I make all copies that I need by

cat runv1.py | tee runv{2..20..1}.py

So I have runv1.py,.., runv20.py. But still the parameter v=1 in all of them.

Q: how can I also replace v parameter to read it from the file name? so e.g in runv4.py then v=4. I would like to know if there is any one-line shell command or combination of commands. Thank you!

PS: direct editing each file is not a proper solution when there are too many files.


Solution

  • Below for loop will serve your purpose I think

    for i in `ls | grep "runv[0-9][0-9]*.py"`
    do
    l=`echo $i | tr -d [a-z.]`
    sed -i 's/v/'"$l"'/g' runv$l.py
    done
    

    Below command was to pass the parameter to script extracted from the filename itself

    ls | grep "runv[0-9][0-9]*.py" | tr -d [a-z.] | awk '{print "./runv"$0".py "$0}' | xargs sh
    

    in the end instead of sh you can use python or bash or ksh.