Linux and Command-Line Basics

$ echo "aaa bab" | sed 's/a/x/'

Which of the following is the output of the sed command above, which replaces characters?

  1. Axaa bab
  2. Bxaa bxb
  3. Cxxx bxb
Show answer and explanation

Answer: A. xaa bab

sed's s/before/after/ replaces only the first match found on each line. The first a on this line is the first character, so the output is xaa bab. To replace every match on the line, add g (global) at the end, as in s/a/x/g, which outputs xxx bxb. Replacement works line by line, so if a file has several lines, the first match on each line is replaced even without g.

  • A. Correct. Without g, only the first a on the line becomes x.
  • B. Replacement is done per line, not per word. Without g, only the first match on the line is replaced.
  • C. This is the output with g added, as in s/a/x/g.
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. In the session above, which of the following is printed by the last awk?
  2. Which of the following describes the files found when find /data -name "*.log" -mtime +7 -size +100M is run with GNU find?
  3. When stopping a process that has stopped responding, it is recommended to first use "kill <process ID>" and to use "kill -9 <process ID>" only if that does not end it. Which of the following is the reason?
  4. While a long-running ./sim.sh is running in a terminal, you want to use other commands in the same terminal. Which of the following is what happens when you press Ctrl+Z and then run bg?
  5. On a server reached over SSH, a long-running task was started with "./run.sh &", and when the connection was closed the task stopped too. Which of the following is the most appropriate way to start it so that it keeps running after the connection is closed?