Để 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?
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 fromgrep
and executes thesed
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).
- 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.
- 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.
- Option D:
awk '/abc/ {gsub("abc", "xyz"); print}' *.txt
awk '/abc/ {gsub("abc", "xyz"); print}' *.txt
: This command usesawk
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 A is the correct answer.