Linux and Command-Line Basics

$ ls
a.log  b.log  notes.txt
$ for f in *.log; do mv "$f" "${f%.log}.txt"; done

Which of the following are the files in the directory after the session above?

  1. Aa.log.txt, b.log.txt, notes.txt
  2. BStill a.log, b.log, notes.txt, with the string ".log" inside a.log and b.log replaced by ".txt"
  3. 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.
Practice this topic Back to topic

Books on Linux and Command-Line Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More Linux and Command-Line Basics questions

  1. An executable script run.sh in the current directory gives "command not found" when run by typing "run.sh", but runs when typed as "./run.sh". Which of the following is the reason?
  2. When the commands above are run in order, which of the following is the pair of outputs of the two bash -c commands?
  3. Which of the following is the main function of a Linux package management system (apt on Debian-based systems, dnf on Red Hat-based systems and so on)?
  4. On a Linux system using systemd, which of the following is the difference between "systemctl start license.service" and "systemctl enable license.service" for the service license.service?
  5. The line "30 2 * * 1 /home/alice/backup.sh" was registered in cron. Which of the following is when backup.sh is run?