파일의 원래 이름에서 문자의 처음 두 인스턴스 사이의 부분을 기반으로 파일 이름을 변경합니다.

파일의 원래 이름에서 문자의 처음 두 인스턴스 사이의 부분을 기반으로 파일 이름을 변경합니다.

처음 두 "|" 인스턴스 사이의 문자열을 기반으로 파일 이름을 변경하려고 합니다. 내 질문은 다음과 같습니다.

>1234|이자 1|임의의 숫자 1.txt

>5678|이자 2|randomstuff2.txt

>9101112|관심 3|randomstuff3|까다로운 것.txt

내가 원하는 출력은 다음과 같습니다.

관심1.txt

Interest2.txt

관심3.txt

정규식과 변수를 사용하여 bash에서 몇 가지 작업을 시도했지만 원하는 결과를 얻을 수 없습니다.

매우 감사합니다!

답변1

Perl 기반 rename유틸리티를 사용하여 이름이 패턴과 일치하는 모든 파일의 이름을 바꿉니다 *interest*.txt. 파이프 기호의 원래 이름을 분할한 다음 끝에 두 번째 결과 필드를 추가하여 .txt각 파일의 이름을 바꿉니다 .

rename -n -v '$_ = (split /\|/)[1] . ".txt"' *interest*.txt

-n명령이 올바른 새 이름을 출력하는지 확인한 후 옵션을 제거하십시오.

질문에 주어진 이름에 대해 테스트하십시오.

$ ls -1
>1234|interest1|randomstuff1.txt
>5678|interest2|randomstuff2.txt
>9101112|interest3|randomstuff3|trickything.txt
$ rename -v '$_ = (split /\|/)[1] . ".txt"' *interest*.txt
>1234|interest1|randomstuff1.txt renamed as interest1.txt
>5678|interest2|randomstuff2.txt renamed as interest2.txt
>9101112|interest3|randomstuff3|trickything.txt renamed as interest3.txt
$ ls -1
interest1.txt
interest2.txt
interest3.txt

답변2

|스크립트는 최소 2개의 문자를 포함하고 로 끝나는 모든 파일 이름을 처리한다고 가정합니다 .txt. 질문의 예제 파일 이름도 일치합니다 *interest*.txt. 요구 사항이 다른 경우 질문에서 이를 명확히 하십시오.

출력이 예상한 것과 같으면 echo앞의 mv내용을 제거하여 실제로 파일 이름을 바꾸십시오. 주석은 # ...코드를 설명하기 위한 것이므로 생략 가능합니다.

for f in *\|*\|*.txt
do
    n="${f#*|}"  # remove leading shortest string matching *|
    n="${n%%|*}" # remove trailing longest string matching |*
    echo mv "$f" "$n".txt
done

답변3

>나는 우리가 로 시작하고 , (적어도) 두 개의 구분 기호( |)를 포함하고, 다음으로 끝나는 파일에 관심이 있다고 가정합니다 .txt.

# Preparation
touch '>1234|interest1|randomstuff1.txt' '>5678|interest2|randomstuff2.txt' '>9101112|interest3|randomstuff3|trickything.txt'

# Process
for f in '>'*'|'*'|'*.txt
do
    x="${f#*|}"                      # Remove from start until first found '|'
    x="${x%%|*}.txt"                 # Remove from first found `|` to end

    printf "%s -> %s\n" "$f" "$x"    # Show what would happen
    # mv -f "$f" "$x"                # Do it (if uncommented)
done

출력(없음 mv)

>1234|interest1|randomstuff1.txt -> interest1.txt
>5678|interest2|randomstuff2.txt -> interest2.txt
>9101112|interest3|randomstuff3|trickything.txt -> interest3.txt

mv파일을 이동하는 명령의 주석 처리를 제거하십시오 . 중복된 대상 이름이 있는 경우 마지막으로 처리된 대상 이름이 유지됩니다.

답변4

perl-rename( 여러 시스템에서 호출된) 경우 rename다음을 수행할 수 있습니다.

$ rename -n 's/.*?\|(.+?)\|.*/$1.txt/' *txt 
>1234|interest1|randomstuff1.txt -> interest1.txt
>5678|interest2|randomstuff2.txt -> interest2.txt
>9101112|interest3|randomstuff3|trickything.txt -> interest3.txt

출력이 원하는 대로 나타나면 -n실제로 파일 이름을 바꾸지 않고 명령을 다시 실행하십시오.

관련 정보