hcdocs
hcdocs

Reputation: 1299

Bash script output not replacing source file content

I would be grateful for education on my question. The goal is to use the filename of an image to create alternate text in Markdown image references for multiple instances in a large number of Markdown files. (I realize from an accessibility standpoint this is a far-from-optimal practice to create alternate text - this is a temporary solution.) For example, I would like:

![](media/image-dir/image-file-with-hyphens.png)

to become

![image file with hyphens](media/image-dir/image-file-with-hyphens.png)

Current script:

for file in *.md; do

while read -r line; do
if [[ $line =~ "![]" ]]; then

# CREATE ALTERNATIVE TEXT OUT OF IMAGE FILENAME
# get text after last instance of / in filepath
processLine=`echo $line |  grep -oE "[^\/]+$"`

# remove image filetypes
processLine2=`echo $processLine | sed 's/.png)//g'`
processLine3=`echo $processLine2 | sed 's/.jpg)//g'`

# remove numbers at end of filename
processLine4=`echo $processLine3 | sed 's/[0-9+]$//g'`

# remove hyphens in filename
processLine5=`echo $processLine4 | sed 's/-/ /g'`

# PUT ALTERNATIVE TEXT IN IMAGE FILEPATH
# trim ![ off front of original line
assembleLine2=`echo $line | sed 's/!\[//g'`

# string together `![` + filename without hyphens + rest of image filepath
assembleLine3='!['"$processLine5"''"$assembleLine2"''

fi
done < $file > $file.tmp && mv $file.tmp $file
done

As it stands, the file comes out blank.

If I add echo $file before while read -r line, the file maintains its original state, but all image references are as follows:

Text

![](media/image-dir/image-file-with-hyphens.png)
![image file with hyphens](media/image-dir/image-file-with-hyphens.png)

Text

If I remove > $file.tmp && mv $file.tmp $file, the console returns nothing.

I've never encountered this in any other Bash script and, at least from the terms I'm using, am not finding the right help in any resource. If anyone is able to help me understand my errors or point me in the right direction, I would be grateful.

Upvotes: 0

Views: 74

Answers (2)

sseLtaH
sseLtaH

Reputation: 11227

If your aim is to replace

![](media/image-dir/image-file-with-hyphens.png)` 

with

![image file with hyphens](media/image-dir/image-file-with-hyphens.png)`, 

then you can try this sed

for file in *.md;
    do sed -E 's/(\S+\[)(\].\S+.)/\1image file with hyphens\2/' "$file" > file.tmp; 
done

Upvotes: 1

Walter A
Walter A

Reputation: 20002

The block of code calculates an assembleLine3, but you don't have echo "${assembleLine3}".
Nothing is written to stdout or to a file.
When you are debugging (or trying to ask a minimal question), remove the first while-loop and most of the processing. Testing the following code is easy:

while read -r line; do
   if [[ $line =~ "![]" ]]; then
      processLine=`echo $line |  grep -oE "[^\/]+$"`
   fi
done < testfile.md

Upvotes: 1

Related Questions