I am a total beginner in this area so sorry if it is a dumb question.
In my shell script I have a variable named FILES, which holds the path to log files, like that:
FILES="./First.log ./Second.log logs/Third.log"
and I want to create a new variable with the same files but different extension, like that:
NEW_FILES="./First.txt ./Second.txt logs/Third.txt"
So I run this command:
NEW_FILES=$(echo "$FILES" | tr ".log" ".txt")
But I get this output:
NEW_FILES="./First.txt ./Secxnd.txt txts/Third.txt"
# ^^^
I understand the .
character is a special character, but I don't know how I can escape it. I have already tried to add a \
before the period but to no avail.
tr
replaces characters with other characters. When you writetr .log .txt
it replaces.
with.
,l
witht
,o
withx
, andg
witht
.To perform string replacement you can use
sed 's/pattern/replacement/g'
, wheres
means substitute andg
means globally (i.e., replace multiple times per line).You could also perform this replacement directly in the shell without any external tools.
The syntax is similar to
sed
, with a global replacement being indicated by two slashes. With a single slash only the first match would be replaced.