0

Suppose, I would like to replace the white-space of the PDF file name with underscore. I know there are so many more easy ways, but I want to do it using bash code. Suppose my python file name is pyFile.py & it contains the following codes:

import re
name = PDFname.replace(" ", "_") # replace any white-space by underscore
print name

And the bash script with file name loop.sh:

#!/bin/bash

for PDFname in *.pdf;
do
    echo $PDFname;
    python pyFile.py
done

How can I do this so that I can use variable Python code which is called through bash script loop?

MKS
  • 199
  • 1
  • 8
  • 1
    If you really want to grab the filename from a shell environment variable, you can use [`os.environ`](https://docs.python.org/3/library/os.html#os.environ). But a more sensible way would be to pass the name as a parameter to the program. – Mark Ransom Dec 16 '21 at 03:37
  • 1
    just double quote the variable name ... https://stackoverflow.com/a/3967765/147175 ... so do this echo "$PDFname" ... then pass this into your python using ... `python pyFile.py "$PDFname" ` then inside your python reference this as argument element 1 since element 0 is name of your python script itself ... as in python code of ... PDFname = sys.argv[1] – Scott Stensland Dec 16 '21 at 03:56
  • @ScottStensland I used your code but shows erros: `python: can't open file 'pyFile.py': [Errno 2] No such file or directory` – MKS Dec 16 '21 at 04:14
  • You seem to be using Python 2 here, which is probably fine for a simple task like this; but going forward, you really want to switch to the currently supported and recommended version of the language, which is Python 3. Version 2 finally went out of support last year. – tripleee Dec 16 '21 at 07:55
  • The absolutely simplest solution is to have your Python script accept more than one file name: `import sys; for file in sys.argv[1:]: print(file.replace(" ", "_"))` and then run `python scriptname.py *.pdf` (also notice you were not using `re` for anything so the `import re` was pointless) – tripleee Dec 16 '21 at 07:58
  • 1
    you need to supply a path to reach the file as per ... `python ./pyFile.py "$PDFname" ` ... which will only work if you are currently cd into same dir as that py file ... otherwise in your bash identify current directory using ... `curr_dir=$( cd $(dirname $0) ; pwd -P )` then make use this ... `python $curr_dir/pyFile.py "$PDFname" ` – Scott Stensland Dec 16 '21 at 12:51
  • 1
    @ScottStensland Thank you very much for your solution. The problem is solved. – MKS Dec 16 '21 at 15:54

0 Answers0