![파일에서 단어(대소문자 구분) 바꾸기](https://rvso.com/image/169413/%ED%8C%8C%EC%9D%BC%EC%97%90%EC%84%9C%20%EB%8B%A8%EC%96%B4(%EB%8C%80%EC%86%8C%EB%AC%B8%EC%9E%90%20%EA%B5%AC%EB%B6%84)%20%EB%B0%94%EA%BE%B8%EA%B8%B0.png)
저는 Linux를 처음 접했고 파일에 200줄이 하나 있습니다. 해당 파일에서 특정 단어를 바꿔야 합니다. 예:기존 단어: foo 새 단어: bar
몇몇 블로그를 읽었는데... sed
. 하지만 쉘 스크립트로 이를 수행하는 방법을 모르겠습니다.
sed 's/foo/bar/' /path to a file
스크립트를 작성해야 하는데, 파일을 입력으로 어떻게 제공해야 할지, 아니면 변수에 저장하고 특정 단어를 변경해야 할지 모르겠습니다.
스크립트는 파일 이름뿐만 아니라 특정 단어도 변경해야 합니다. 예: 입력 파일 이름: cat home.txt(바꿀 단어 -->cat) 출력 파일 이름: Dog home.txt(Cat은 Dog로 바꿔야 함)
친절하게 도와주세요!
답변1
foo
문자열을 변경 하려면 bar
다음을 사용할 수 있습니다.
#!/bin/bash
# the pattern we want to search for
search="foo"
# the pattern we want to replace our search pattern with
replace="bar"
# my file
my_file="/path/to/file"
# generate a new file name if our search-pattern is contained in the filename
my_new_file="$(echo ${my_file} | sed "s/${search}/${replace}/")"
# replace all occurrences of our search pattern with the replace pattern
sed -i "s/${search}/${replace}/g" "${my_file}"
# rename the file to the new filename
mv "${my_file}" "${my_new_file}"
검색 패턴이 단어의 일부와 일치하는 경우 해당 부분도 대체됩니다. 예:
"나에겐 애벌레가 있어요."
"cat"이라는 검색 문자열과 "dog"라는 대체 문자열을 사용하면 다음과 같습니다.
"나에겐 개기둥이 있어요."
불행히도 이것을 피하는 것은 완전히 사소한 일이 아닙니다.