다른 명령의 출력을 사용하여 파일 이름을 바꾸는 한 줄짜리 명령

다른 명령의 출력을 사용하여 파일 이름을 바꾸는 한 줄짜리 명령

파일에서 단어를 추출하는 명령이 있습니다.

추출한 단어를 사용하여 해당 파일의 이름을 바꾸고 싶습니다.

나중에 이름을 바꾸는 데 사용할 단어를 추출하는 데 사용하는 명령파일명.txt, 다음과 같습니다:

$ grep -e "some words" -e "other words" filename.txt | awk '{print $1}' 

파일명.txt콘텐츠 예:

dasdadas
asdasda
asdas
matched some words
asdas
asda

예상 결과:파일명.txt다음으로 이름이 변경됩니다.일치.txt.

나는 이것이 한 줄짜리 명령을 사용하여 수행될 수 있기를 바랍니다.

이것은 작동하지 않지만 다음과 같을 수도 있습니다.

mv filename.txt $(grep -e "some words" -e "other words" filename.txt | awk '{print $1}').txt Note: Im certain that there will only be one match with thegrep`. 감사해요.

답변1

#!/bin/bash 
old_file_name=$1  # take an argument for the file you want to muck with
new_file_name=$(grep -e "some words" -e "other words" "${old_file_name}" | awk '{print $1}' | head -n 1).txt 
mv "$old_file_name" "$new_file_name"

답변2

단일 파이프라인에서 grepand 를 사용하는 것은 거의 좋은 생각이 아닙니다. 왜냐하면 can은 모든 것을 할 수 있기 때문 입니다:awkawkgrep

awk '/(some|other) words/ {print $1}' filename.txt | xargs -I{} mv filename.txt {}.txt

관련 정보