Linux and Command-Line Basics
$ ls
a.log b.log notes.txt
$ for f in *.log; do mv "$f" "${f%.log}.txt"; doneWhich of the following are the files in the directory after the session above?
- Aa.log.txt, b.log.txt, notes.txt
- BStill a.log, b.log, notes.txt, with the string ".log" inside a.log and b.log replaced by ".txt"
- Ca.txt, b.txt, notes.txt
Show answer and explanation
Answer: C. a.txt, b.txt, notes.txt
for f in *.log puts a.log and b.log, which match *.log, into the variable f one at a time and repeats the part between do and done. ${f%.log} is the value of f with .log removed from the end, so for a.log it is a, and mv "$f" "${f%.log}.txt" renames a.log to a.txt. notes.txt does not match *.log and is left as is. "$f" is enclosed in double quotes so that a name containing spaces is passed to mv as a single argument.
- A. This is the result of writing mv "$f" "$f.txt". ${f%.log} removes the trailing .log.
- B. mv renames files and does not change their contents. Replacing contents is done with sed and similar tools.
- C. Correct. The names change to have the trailing .log removed and .txt added.