UNIX change all the file extension for a list of files

56 views Asked by At

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.

2

There are 2 answers

0
John Kugelman On BEST ANSWER

tr replaces characters with other characters. When you write tr .log .txt it replaces . with ., l with t, o with x, and g with t.

To perform string replacement you can use sed 's/pattern/replacement/g', where s means substitute and g means globally (i.e., replace multiple times per line).

NEW_FILES=$(echo "$FILES" | sed 's/\.log/.txt/g')

You could also perform this replacement directly in the shell without any external tools.

NEW_FILES=${FILES//\.log/.txt}

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.

2
vdavid On

tr is not the tool you need. The goal of tr is to change characters on a 1-by-1 basis. You probably did not see it, but Second must have been changed to Secxnd.

I think sed is better.

NEW_FILES=$(sed 's/\.log/.txt/g' <<< $FILES)

It searches the \.log regular expression and replaces it with the .txt string. Please note the \. in the regex which means that it matches the dot character . and nothing else.