JavaScript is required

Để tìm kiếm và thay thế chuỗi "abc" bằng "xyz" trong tất cả các tập tin .txt trong thư mục hiện tại, bạn sẽ sử dụng câu lệnh nào?

A.

grep -rl 'abc' . | xargs sed -i 's/abc/xyz/g'

B.

sed -i 's/abc/xyz/g' .txt

C.

find . -type f -name '.txt' | xargs sed -i 's/abc/xyz/g'

D.

awk '/abc/ {gsub("abc", "xyz"); print}' *.txt

Trả lời:

Đáp án đúng: C


The goal is to find and replace a string in multiple files. Specifically, we need to find ".txt" files in the current directory and replace the string "abc" with "xyz".

  • Option A: grep -rl 'abc' . | xargs sed -i 's/abc/xyz/g'
    • grep -rl 'abc' .: This command searches for all files in the current directory (.) that contain the string "abc" and prints a list of those files. The -r parameter means recursive search (in all subdirectories), and -l means only print the names of files containing the search string.
    • xargs sed -i 's/abc/xyz/g': This command receives the list of files from grep and executes the sed command on each file. sed -i 's/abc/xyz/g' replaces all occurrences of "abc" with "xyz" in each file. The -i parameter means modify the original file directly. s/abc/xyz/g is the substitution command in sed, replacing 'abc' with 'xyz' globally (g - global).
    Therefore, option A correctly performs the task.
  • Option B: sed -i 's/abc/xyz/g' .txt
    • This command attempts to replace directly in a file named ".txt", not in all ".txt" files in the directory. Also, it doesn't search for files but only acts on the ".txt" file if it exists.
    Therefore, option B is incorrect.
  • Option C: find . -type f -name '.txt' | xargs sed -i 's/abc/xyz/g'
    • find . -type f -name '.txt': This command finds all files (-type f) named (-name) ".txt" in the current directory (.). However, it only finds files with the exact name ".txt" and not files with the ".txt" extension. For example, it will find the file ".txt" but not the file "example.txt". A correct find command would be `find . -type f -name '*.txt'` to find all files with `.txt` extension.
    Although the syntax is close, the file name search method is incorrect. This command will only find the file named ".txt" and not other files with the ".txt" extension. Therefore, option C is incorrect.
  • Option D: awk '/abc/ {gsub("abc", "xyz"); print}' *.txt
    • awk '/abc/ {gsub("abc", "xyz"); print}' *.txt: This command uses awk to find lines containing "abc" in ".txt" files and replace "abc" with "xyz" on those lines, then print the modified lines to the screen. However, it does not directly modify the files.
    Therefore, option D is incorrect because it only prints the replacement result and does not write to the files.

Therefore, option A is the correct answer.

Câu hỏi liên quan