할리와 같은 특정 단어의 가능한 모든 소문자 및 대문자 순열을 인쇄하기 위해 bash 스크립트를 작성하고 싶습니다.
harley
harleY
harlEy
harLey
...
HARLey
HARLEy
HARLEY
내 순진한 해결책은이 특정 단어에 대해 n 번째 (n is len (word)) 중첩 for 루프를 작성하는 것입니다.
#!/bin/bash
for a in {h,H}; do
for b in {a,A}; do
...
done
done
그러나 스크립트를 다른 단어로 다시 코딩해야합니다.
이것을 달성하는 더 좋은 방법이 있습니까?
답변
약간 더 나은 해결책 :
echo {h,H}{a,A}{r,R}{l,L}{e,E}{y,Y}
완벽한 확장 성을 위해 :
echo harley \
| perl -nle 'print "echo ",
join "",map { "{" . lc . "," .uc ."}" } split //' \
| xargs -I {} bash -c "{}"
한 줄에 하나의 단어가 있어야한다면
for w in {h,H}{a,A}{r,R}{l,L}{e,E}{y,Y};do echo $w;done
mattdm의 의견 덕분에
해당 확장 가능 버전은 다음과 같습니다.
echo harley \
| perl -nle 'print join "",map { "{" . lc . "," .uc ."}" } split //' \
| xargs -I {} bash -c 'for w in {};do echo $w;done'
재미를 위해, “harley”를 “supercalifragilisticexpialidocious”로 교체해보십시오. 5 분이 지났는데 컴퓨터가 여전히이 컴퓨터에서 작동하지 않고 아마 끝나지 않을 것입니다. 🙂
답변
eval echo $ (echo " word "| sed 's /./ {\ U &, \ L &} / g')
sed 's/./{&,&}/g'
될지는Foo
에{F,F}{o,o}{o,o}
꽤 쓸모가있을 것이다. 그러나 추가\U
하고\L
당신은 각 문자의 대문자와 소문자를 얻을; 즉{F,f}{O,o}{O,o}
.- 그런 다음
eval
쉘에게 { X , x } 괄호 시퀀스 를 확장하도록 지시 하는 것은 간단한 문제입니다 .
답변
편집 2 : 이 답변이 잘못되었습니다. 2 ^ n 조합을 생성하지 않습니다.
편집 : 나는 이유는 모르겠지만,이 솔루션이되어 정말 빠른 미만 0.3 초에 @Joeseph R.에 의해 펄 솔루션에 비해 그것은 “Supercalifragilisticexpialidocious”를 실행!
여기 내 균열이 있습니다.
#!/bin/bash
str=${1^^} # convert to uppercase
len=${#str} # get length of string
for ((perm=0; perm <= len; perm++)); do
for ((i=0; i <= len; i++)); do
lower=${str,,} # convert to lowercase
# Uppercase n-th letter for permutation
if [ $perm -gt 0 ]; then
nth=${lower:perm-1}
lower=$(echo ${lower:0:perm-1}${nth^})
fi
echo -n ${str:0:i} # print orig string from 0 to $i
echo ${lower:i} # print new string from $i to end
done
done | sort -u
그것을 실행 :
$ ./permutations.sh hi
hi
hI
Hi
HI
$ ./permutations.sh harley
harley
harleY
harlEy
harLey
haRley
hArley
Harley
HarleY
HarlEy
HarLey
HaRley
HArley
HArleY
HArlEy
HArLey
HARley
HARleY
HARlEy
HARLey
HARLeY
HARLEy
HARLEY
자유롭게 포크하고 수정하면 최적화 될 수 있다고 확신합니다. https://gist.github.com/ryanmjacobs/4c02ad80f833dee0c307
답변
코딩 대신 준비된 도구를 사용하려면 TextMechanic (순열 / 조합 생성기 도구) 및 Unit-Conversion.info를 사용할 수 있습니다.