Bash에서 문자를 반복하려면 어떻게 해야 하나요?
요?echo
perl -E 'say "=" x 100'
다음을 사용할 수 있습니다.
printf '=%.0s' {1..100}
동작 구조:
{1..100}츠키다
printf '=%.0s' 1 2 3 4 ... 100
을 printf로 =%.0s, 항상 의 「」, 「1」이 됩니다.=★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 100을 합니다.=s.
쉬운 방법이 아니다.단, 예를 들어 다음과 같습니다.
seq -s= 100|tr -d '[:digit:]'
# Editor's note: This requires BSD seq, and breaks with GNU seq (see comments)
또는 다음과 같은 표준 적합 방법을 사용할 수 있습니다.
printf %100s |tr " " "="
'아주머니'라는 것도 있어요.tput rep 현재 사용하고 있는 및 되지 않는 것
@gniourf_gniourf에 대한 입력에 대한 모자의 팁.
주의: 이 답변은 원래 질문에 대한 답변이 아니라 성능을 비교하여 기존의 유용한 답변을 보완합니다.
솔루션은 실행 속도에 대해서만 비교됩니다.메모리 요건은 고려되지 않습니다(솔루션마다 다르며 반복 횟수가 많을 경우 문제가 될 수 있습니다).
요약:.
- 반복 횟수가 약 100회 정도라면 외부 유틸리티, 특히 Perl의 시작 비용이 중요하기 때문에 Bash 전용 솔루션을 사용하는 것이 좋습니다.
- 다만, 실용적으로 말하면, 1개의 반복 문자의 인스턴스만 필요한 경우는, 기존의 모든 솔루션이 문제가 없는 경우가 있습니다.
- 반복 횟수가 많을 경우 외부 유틸리티를 사용하면 훨씬 빠릅니다.
- 에 큰 은 사용하지 .
(예:${var// /=}매우 느리기 때문입니다.
- 에 큰 은 사용하지 .
다음은 3.2GHz Intel Core i5 CPU와 Fusion 드라이브를 탑재한 2012년 후반의 iMac에서 OSX 10.10.4 및 bash 3.2.57을 실행하는 타이밍으로 측정한 평균 실행 횟수입니다.
엔트리는 다음과 같습니다.
- 실행 기간의 오름차순으로 나열됨(먼저 표시됨)
- ★★★★★★★★★★★★★★★★★★:
M...다문자화솔루션가능성S...한글자만의솔루션PPOSIX 거 pos pos pos
- 그 후 솔루션에 대한 간단한 설명이 이어집니다.
- 원답의 저자 이름이 붙어 있다
- 작은 반복 횟수: 100
[M, P] printf %.s= [dogbane]: 0.0002
[M ] printf + bash global substr. replacement [Tim]: 0.0005
[M ] echo -n - brace expansion loop [eugene y]: 0.0007
[M ] echo -n - arithmetic loop [Eliah Kagan]: 0.0013
[M ] seq -f [Sam Salisbury]: 0.0016
[M ] jot -b [Stefan Ludwig]: 0.0016
[M ] awk - $(count+1)="=" [Steven Penny (variant)]: 0.0019
[M, P] awk - while loop [Steven Penny]: 0.0019
[S ] printf + tr [user332325]: 0.0021
[S ] head + tr [eugene y]: 0.0021
[S, P] dd + tr [mklement0]: 0.0021
[M ] printf + sed [user332325 (comment)]: 0.0021
[M ] mawk - $(count+1)="=" [Steven Penny (variant)]: 0.0025
[M, P] mawk - while loop [Steven Penny]: 0.0026
[M ] gawk - $(count+1)="=" [Steven Penny (variant)]: 0.0028
[M, P] gawk - while loop [Steven Penny]: 0.0028
[M ] yes + head + tr [Digital Trauma]: 0.0029
[M ] Perl [sid_com]: 0.0059
- Bash 전용 솔루션이 선두를 달리고 있지만 반복 횟수가 이 정도로 적습니다(아래 참조).
- 여기에는 외부 유틸리티, 특히 Perl의 초기 비용이 중요합니다.반복 횟수가 적은 루프에서 호출해야 하는 경우 다중 유틸리티를 피하십시오.
awk, , , , 입니다.perl★★★★★★★★★★★★★★★★★★.
- 대량 반복 횟수: 1000000 (100만)
[M ] Perl [sid_com]: 0.0067
[M ] mawk - $(count+1)="=" [Steven Penny (variant)]: 0.0254
[M ] gawk - $(count+1)="=" [Steven Penny (variant)]: 0.0599
[S ] head + tr [eugene y]: 0.1143
[S, P] dd + tr [mklement0]: 0.1144
[S ] printf + tr [user332325]: 0.1164
[M, P] mawk - while loop [Steven Penny]: 0.1434
[M ] seq -f [Sam Salisbury]: 0.1452
[M ] jot -b [Stefan Ludwig]: 0.1690
[M ] printf + sed [user332325 (comment)]: 0.1735
[M ] yes + head + tr [Digital Trauma]: 0.1883
[M, P] gawk - while loop [Steven Penny]: 0.2493
[M ] awk - $(count+1)="=" [Steven Penny (variant)]: 0.2614
[M, P] awk - while loop [Steven Penny]: 0.3211
[M, P] printf %.s= [dogbane]: 2.4565
[M ] echo -n - brace expansion loop [eugene y]: 7.5877
[M ] echo -n - arithmetic loop [Eliah Kagan]: 13.5426
[M ] printf + bash global substr. replacement [Tim]: n/a
- 질문의 Perl 솔루션이 가장 빠릅니다.
- 치환(Bash)
${foo// /=})는 큰 스트링에서는 설명할 수 없을 정도로 느리고 실행에서 제외되어 있습니다(Bash 4.3.30에서는 약 50분(!), Bash 3.2.57에서는 더 오래 걸립니다.(을) - 루프Bash " " " " " " " )
(( i= 0; ... ))는, 삽입 )보다 .{1..n}- 효율이 더 높지만 - 、 、 、 、 ) are are are ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ). awkBSD를 참조합니다.awk에서도 볼 수 - (OSX에서 볼 수 있는) - (OSX에서 볼 수 있는) - (OSX에서 볼 수 있는) - (OSX에서 볼 수 있는 보다 현저하게 느립니다.gawkGNU 및 (GNU Awk) ★★mawk.- 큰 카운트와 멀티 문자 문자열에서는 메모리 소비량이 고려 대상이 될 수 있습니다.이러한 접근방식은 그 점에서 다릅니다.
여기 Bash 스크립트(testrepeat )을 참조해 주세요을 사용하다두 번째, 2번, 2번, 2번, 2번
- 문자 반복 횟수
- 선택적으로 수행할 테스트 런의 수 및 평균 타이밍을 계산합니다.
은, 「」, 「」, 「」, 「」로 취득했습니다.testrepeat 100 1000 ★★★★★★★★★★★★★★★★★」testrepeat 1000000 1000
#!/usr/bin/env bash
title() { printf '%s:\t' "$1"; }
TIMEFORMAT=$'%6Rs'
# The number of repetitions of the input chars. to produce
COUNT_REPETITIONS=${1?Arguments: <charRepeatCount> [<testRunCount>]}
# The number of test runs to perform to derive the average timing from.
COUNT_RUNS=${2:-1}
# Discard the (stdout) output generated by default.
# If you want to check the results, replace '/dev/null' on the following
# line with a prefix path to which a running index starting with 1 will
# be appended for each test run; e.g., outFilePrefix='outfile', which
# will produce outfile1, outfile2, ...
outFilePrefix=/dev/null
{
outFile=$outFilePrefix
ndx=0
title '[M, P] printf %.s= [dogbane]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
# !! In order to use brace expansion with a variable, we must use `eval`.
eval "
time for (( n = 0; n < COUNT_RUNS; n++ )); do
printf '%.s=' {1..$COUNT_REPETITIONS} >"$outFile"
done"
title '[M ] echo -n - arithmetic loop [Eliah Kagan]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
for ((i=0; i<COUNT_REPETITIONS; ++i)); do echo -n =; done >"$outFile"
done
title '[M ] echo -n - brace expansion loop [eugene y]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
# !! In order to use brace expansion with a variable, we must use `eval`.
eval "
time for (( n = 0; n < COUNT_RUNS; n++ )); do
for i in {1..$COUNT_REPETITIONS}; do echo -n =; done >"$outFile"
done
"
title '[M ] printf + sed [user332325 (comment)]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
printf "%${COUNT_REPETITIONS}s" | sed 's/ /=/g' >"$outFile"
done
title '[S ] printf + tr [user332325]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
printf "%${COUNT_REPETITIONS}s" | tr ' ' '=' >"$outFile"
done
title '[S ] head + tr [eugene y]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
head -c $COUNT_REPETITIONS < /dev/zero | tr '\0' '=' >"$outFile"
done
title '[M ] seq -f [Sam Salisbury]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
seq -f '=' -s '' $COUNT_REPETITIONS >"$outFile"
done
title '[M ] jot -b [Stefan Ludwig]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
jot -s '' -b '=' $COUNT_REPETITIONS >"$outFile"
done
title '[M ] yes + head + tr [Digital Trauma]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
yes = | head -$COUNT_REPETITIONS | tr -d '\n' >"$outFile"
done
title '[M ] Perl [sid_com]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
perl -e "print \"=\" x $COUNT_REPETITIONS" >"$outFile"
done
title '[S, P] dd + tr [mklement0]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
dd if=/dev/zero bs=$COUNT_REPETITIONS count=1 2>/dev/null | tr '\0' "=" >"$outFile"
done
# !! On OSX, awk is BSD awk, and mawk and gawk were installed later.
# !! On Linux systems, awk may refer to either mawk or gawk.
for awkBin in awk mawk gawk; do
if [[ -x $(command -v $awkBin) ]]; then
title "[M ] $awkBin"' - $(count+1)="=" [Steven Penny (variant)]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
$awkBin -v count=$COUNT_REPETITIONS 'BEGIN { OFS="="; $(count+1)=""; print }' >"$outFile"
done
title "[M, P] $awkBin"' - while loop [Steven Penny]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
$awkBin -v count=$COUNT_REPETITIONS 'BEGIN { while (i++ < count) printf "=" }' >"$outFile"
done
fi
done
title '[M ] printf + bash global substr. replacement [Tim]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
# !! In Bash 4.3.30 a single run with repeat count of 1 million took almost
# !! 50 *minutes*(!) to complete; n Bash 3.2.57 it's seemingly even slower -
# !! didn't wait for it to finish.
# !! Thus, this test is skipped for counts that are likely to be much slower
# !! than the other tests.
skip=0
[[ $BASH_VERSINFO -le 3 && COUNT_REPETITIONS -gt 1000 ]] && skip=1
[[ $BASH_VERSINFO -eq 4 && COUNT_REPETITIONS -gt 10000 ]] && skip=1
if (( skip )); then
echo 'n/a' >&2
else
time for (( n = 0; n < COUNT_RUNS; n++ )); do
{ printf -v t "%${COUNT_REPETITIONS}s" '='; printf %s "${t// /=}"; } >"$outFile"
done
fi
} 2>&1 |
sort -t$'\t' -k2,2n |
awk -F $'\t' -v count=$COUNT_RUNS '{
printf "%s\t", $1;
if ($2 ~ "^n/a") { print $2 } else { printf "%.4f\n", $2 / count }}' |
column -s$'\t' -t
방법은 여러 가지가 있습니다.
루프 사용:
가새 확장은 정수 리터럴과 함께 사용할 수 있습니다.
for i in {1..100}; do echo -n =; doneC와 같은 루프에서는 다음 변수를 사용할 수 있습니다.
start=1 end=100 for ((i=$start; i<=$end; i++)); do echo -n =; done
「 」의 printf★★★★
printf '=%.0s' {1..100}
너비에 (자세한 내용은 생략).0 입니다.printf, 「인수」가 됩니다.이것은 단순히 출력됩니다."="곱하기 100파운드
「」를 사용합니다.head )printf및 ( 등)tr:
head -c 100 < /dev/zero | tr '\0' '='
printf %100s | tr " " "="
seq를 사용하여 이 작업을 수행할 수 있는 매우 쉬운 방법을 방금 찾았습니다.
은 BSD에서 합니다: BSD에서 동작합니다.seqOS X os os os os 。YMMV를 사용하다
seq -f "#" -s '' 10
다음과 같이 '#'을 10회 인쇄합니다.
##########
-f "#"하고 형식 을 설정하여 합니다.#각각에 대해서요.-s ''가 각 를 빈 합니다.- ' ' 뒤에 있는 '
-f★★★★★★★★★★★★★★★★★」-s중요한 것 같아요.
편집: 여기 편리한 기능이 있습니다.
repeat () {
seq -f $1 -s '' $2; echo
}
이렇게 부르면...
repeat "#" 10
주의: 반복하는 경우#아아아!
여기 두 가지 흥미로운 방법이 있습니다.
ubuntu@ubuntu:~$ yes = | 헤드 -10 | 페이스트 -s -d " -==========ubuntu@ubuntu:~$ yes = | head - 10 | tr - d " \ n "==========ubuntu@ubuntu:~$
두 는 것에 해 주세요.paste메서드는 새 행으로 끝납니다.tr메서드는 그렇지 않습니다.
간단한 방법은 없어요.를 사용하지 printf★★★★★★ 。
str=$(printf "%40s")
echo ${str// /rep}
# echoes "rep" 40 times.
는 ' 하면 였습니다.echo:
echo -e ''$_{1..100}'\b='
.perl -E 'say "=" x 100', 하하와 함께echodisclossible.
없는 순수한 배쉬 방식eval 툴,를 가질 수 : , 「 」, 「 」, 「 」, 「 」( 「 」: 「 」)입니다.
경우n(음수로 됩니다.pattern ...timeout,
$ n=5
$ pattern=hello
$ printf -v output '%*s' "$n"
$ output=${output// /$pattern}
$ echo "$output"
hellohellohellohellohello
다음과 같이 함수를 만들 수 있습니다.
repeat() {
# $1=number of patterns to repeat
# $2=pattern
# $3=output variable name
local tmp
printf -v tmp '%*s' "$1"
printf -v "$3" '%s' "${tmp// /$2}"
}
이 세트에서는:
$ repeat 5 hello output
$ echo "$output"
hellohellohellohellohello
리리쓰 for for for for for for for for for for for for for for for for for for for for for for for를 사용하고 있습니다.printf하다
-v varname: " " " " " "printf을 변수 "예"에 넣습니다.varname.- '%*s':
printf예를 들어,printf '%*s' 4242번입니다. - 이 있는 확장을 으로 바꿉니다.예를 들어 파라미터 공백이 패턴으로 대체됩니다.
${var// /$pattern}의 확대로 확대되다var이 「」의 .$pattern.
, 「 」, 「 」를 할 수도 있습니다.tmp the variable in 수 variable 。repeat간접 확장을 사용하여 기능합니다.
repeat() {
# $1=number of patterns to repeat
# $2=pattern
# $3=output variable name
printf -v "$3" '%*s' "$1"
printf -v "$3" '%s' "${!3// /$2}"
}
POSIX 에 필요한 echo ★★★★★★★★★★★★★★★★★」printf 및 "/" 의 셸)bash:
seq(){ n=$1; while [ $n -le $2 ]; do echo $n; n=$((n+1)); done ;} # If you don't have it.
echo $(for each in $(seq 1 100); do printf "="; done)
와 같은 수 .와 같은 출력을 얻을 수 있습니다.perl -E 'say "=" x 100'모든 곳에서요
#!/usr/bin/awk -f
BEGIN {
OFS = "="
NF = 100
print
}
또는
#!/usr/bin/awk -f
BEGIN {
while (z++ < 100) printf "="
}
다음은 Linux에서 화면 전체에 한 줄의 문자를 인쇄하기 위해 사용하는 것입니다(단말기/화면 너비 기준).
화면에 "="를 인쇄합니다.
printf '=%.0s' $(seq 1 $(tput cols))
설명:
지정된 시퀀스 횟수만큼 등호를 인쇄합니다.
printf '=%.0s' #sequence
명령어의 출력을 사용합니다(이것은 Command Substitution이라고 하는 bash 기능).
$(example_command)
예를 들어 1번에서 20번 정도 썼는데 순서를 알려주세요.마지막 명령어에서는 tput 명령어가 20 대신 사용됩니다.
seq 1 20
터미널에서 현재 사용되는 열의 수를 지정합니다.
tput cols
임의의 문자열을 n회 반복하는 다른 수단:
장점:
- POSIX 쉘에서 동작합니다.
- 출력은 변수에 할당할 수 있습니다.
- 임의의 문자열을 반복합니다.
- 반복 횟수가 매우 많아도 매우 빠릅니다.
단점:
- Gnu가 합니다.
yes명령어를 입력합니다.
#!/usr/bin/sh
to_repeat='='
repeat_count=80
yes "$to_repeat" | tr -d '\n' | head -c "$repeat_count"
ANSI 단말기와 US-ASCII 문자를 반복한다.ANSI CSI 이스케이프 시퀀스를 사용할 수 있습니다.그것은 캐릭터를 반복하는 가장 빠른 방법이다.
#!/usr/bin/env bash
char='='
repeat_count=80
printf '%c\e[%db' "$char" "$repeat_count"
또는 정적:
x 80 쇄의 합니다.=:
printf '=\e[80b\n'
제한 사항:
- 가 이 기능을 할 수 것은 아닙니다.
repeat_charANSI CSI 시 ansi ansi - US-ASCII 문자 또는 싱글바이트 ISO 문자만 반복할 수 있습니다.
- 마지막 열에서 중지를 반복하여 큰 값을 사용하여 단자 폭에 관계없이 전체 라인을 채울 수 있습니다.
- 을 사용하다을 셸 해도 " "는 .
repeat_charANSI CSI는 ANSI CSI를 사용합니다.
printf 및 tr을 사용한 다른 bash 솔루션
nb. 시작하기 전에:
- 다른 답이 필요한가요?아마 아닐 거예요.
- 이 답이 벌써 여기 있나요?안 보이니까, 간다.
의 선두 패딩 합니다.printf을 0으로 할 때 사용합니다.tr 모든 것이 {1..N}★★★★★★★★★★★★★★★★★★:
$ printf '%040s' | tr '0' '='
========================================
너비를 'N'자로 설정하고 인쇄된 문자를 사용자 지정하려면:
#!/usr/bin/env bash
N=40
C='-'
printf "%0${N}s" | tr '0' "${C}"
큰 N의 경우 발전기보다 성능이 훨씬 우수합니다. 내 기계(bash 3.2.57)에서는:
$ time printf '=%.0s' {1..1000000} real: 0m2.580s
$ time printf '%01000000s' | tr '0' '=' real: 0m0.577s
bash 3.0 이후
for i in {1..100};do echo -n =;done
질문의 원래 목적은 셸의 내장 명령어만으로 이 작업을 수행하는 것이었다고 생각합니다. ★★★★★★★★★★★★★★★★★.for와 ""printf이며 s는 정규입니다.rep,perl및 , 「」도 있습니다.jot아래는 그렇지 않습니다.
jot -s "/" -b "\\" $((COLUMNS/2))
를 들어,창 행에 "예" "예" "예" "예" "예" "예" "예" "예" "예" "예:\/\/\/\/\/\/\/\/\/\/\/\/
다른 사람이 말했듯이 bash brase에서는 파라미터 확장보다 확장이 우선합니다.{m,n}범위에는 리터럴만 포함할 수 있습니다.또, 클린 솔루션을 제공할 수 있지만, 각 시스템에서 같은 셸을 사용하고 있는 경우에서도, 시스템간에 완전하게 이식할 수 있는 것은 아닙니다.seq는 FreeBSD 9.3 이후 등 가용성이 높아지고 있습니다.또, 다른 형식의 간접은 항상 기능하지만, 다소 서툴러집니다.
다행히 bash는 루프에 대해 C-style을 지원합니다(산술식만 사용).그럼, 「순수한 bash」라고 하는 간결한 방법이 있습니다.
repecho() { for ((i=0; i<$1; ++i)); do echo -n "$2"; done; echo; }
이 명령어는 반복 횟수를 첫 번째 인수로 사용하고 반복되는 문자열(문제 설명과 같이 단일 문자일 수 있음)을 두 번째 인수로 사용합니다. repecho 7 b 력 outputsbbbbbbb(서양속담, 친구속담)
Dennis Williamson은 4년 전 쉘 스크립트에서 일련의 반복 캐릭터 생성에 대한 훌륭한 답변으로 이 해결책을 제시했습니다.내 기능 본체는 코드와 약간 다릅니다.
한bash이기 에 bash를 할 것입니다.
echoprintf이 은 인쇄echo위의 함수 정의는 bash 및 ksh93으로 동작합니다.비록 ~일지라도printf이런).echo의 구문은 거의 틀림없이 더 읽기 쉬울 것입니다.개의 조개껍데기
echo는 " "를 해석합니다.-으로서 그 인 「이러한 의미」를 사용해도--------------------------------------------------------------------------------------------------------------------을 사용하는 「stdin」에 대해서는 가 없습니다.echo.zsh는 이렇게 합니다.그리고 분명히 존재한다.echo인식되지 않는-n표준이 아니기 때문에 (많은 Bourne 스타일의 셸은 루프를 위한 C-style을 전혀 받아들이지 않습니다.따라서,echo을 사용하다여기서는 시퀀스를 인쇄하고, 여기서는 변수를 할당하는 작업입니다.
if$n원하는 반복 횟수이므로 재사용할 필요가 없습니다.또, 보다 짧은 것이 필요하게 됩니다.
while ((n--)); do echo -n "$s"; done; echo
n변수여야 합니다. 이 방법은 위치 매개 변수와 함께 사용할 수 없습니다. $s반복되는 텍스트입니다.
Python은 어디에나 존재하며 어디에서나 동일하게 작동합니다.
python -c "import sys; print('*' * int(sys.argv[1]))" "=" 100
문자와 카운트는 별도의 파라미터로 전달됩니다.
제안된 Python 솔루션에 대한 보다 우아한 대안은 다음과 같습니다.
python -c 'print "="*(1000)'
가장 간단한 방법은 csh/tcsh에서 다음 원라이너를 사용하는 것입니다.
printf "%50s\n" '' | tr '[:blank:]' '[=]'
repeat() {
# $1=number of patterns to repeat
# $2=pattern
printf -v "TEMP" '%*s' "$1"
echo ${TEMP// /$2}
}
이것은 Eliah Kagan이 주장했던 것의 긴 버전입니다.
while [ $(( i-- )) -gt 0 ]; do echo -n " "; done
물론 printf도 사용할 수 있지만, 제 취향에는 맞지 않습니다.
printf "%$(( i*2 ))s"
이 버전은 Dash 호환 버전입니다.
until [ $(( i=i-1 )) -lt 0 ]; do echo -n " "; done
첫 번째 번호가 i인 채로요
또 다른 옵션은 GNU seq를 사용하여 생성된 모든 번호와 줄바꿈을 삭제하는 것입니다.
seq -f'#%.0f' 100 | tr -d '\n0123456789'
는 " " 를 합니다.# 100 .1005입니다.
쌓기 위해서가 아니라, 또 다른 순수한 Bash 접근법은${//}다음 중 하나:
$ arr=({1..100})
$ printf '%s' "${arr[@]/*/=}"
====================================================================================================
for i in {1..100}
do
echo -n '='
done
echo
예를 들어 문자열의 길이에 따라 n개의 문자를 n개의 VARILE 횟수만큼 반복할 수 있습니다.
#!/bin/bash
vari='AB'
n=$(expr 10 - length $vari)
echo 'vari equals.............................: '$vari
echo 'Up to 10 positions I must fill with.....: '$n' equal signs'
echo $vari$(perl -E 'say "=" x '$n)
다음과 같이 표시됩니다.
vari equals.............................: AB
Up to 10 positions I must fill with.....: 8 equal signs
AB========
function repeatString()
{
local -r string="${1}"
local -r numberToRepeat="${2}"
if [[ "${string}" != '' && "${numberToRepeat}" =~ ^[1-9][0-9]*$ ]]
then
local -r result="$(printf "%${numberToRepeat}s")"
echo -e "${result// /${string}}"
fi
}
샘플 실행
$ repeatString 'a1' 10
a1a1a1a1a1a1a1a1a1a1
$ repeatString 'a1' 0
$ repeatString '' 10
레퍼런스 lib: https://github.com/gdbtek/linux-cookbooks/blob/master/libraries/util.bash
어떻게 에코를 가지고 이걸 할 수 있죠?
, 하다, 하다, 하다, 이렇게 할 수 요.echoecho 에 가 있다sed:
echo | sed -r ':a s/^(.*)$/=\1/; /^={100}$/q; ba'
그 ★★★★★★★★★★★★★★★★★★★.echo필요합합니니다
조금 더 복잡해서 완벽하지 않을 수도 있지만, 큰 숫자를 출력하고 싶은 분들을 위해 3초 만에 1000만 개 정도를 할 수 있었습니다.
repeatString(){
# argument 1: The string to print
# argument 2: The number of times to print
stringToPrint=$1
length=$2
# Find the largest integer value of x in 2^x=(number of times to repeat) using logarithms
power=`echo "l(${length})/l(2)" | bc -l`
power=`echo "scale=0; ${power}/1" | bc`
# Get the difference between the length and 2^x
diff=`echo "${length} - 2^${power}" | bc`
# Double the string length to the power of x
for i in `seq "${power}"`; do
stringToPrint="${stringToPrint}${stringToPrint}"
done
#Since we know that the string is now at least bigger than half the total, grab however many more we need and add it to the string.
stringToPrint="${stringToPrint}${stringToPrint:0:${diff}}"
echo ${stringToPrint}
}
가장 간단한 방법은 bash에서 다음 한 줄을 사용하는 것입니다.
seq 10 | xargs -n 1 | xargs -I {} echo -n ===\>;echo
언급URL : https://stackoverflow.com/questions/5349718/how-can-i-repeat-a-character-in-bash
'programing' 카테고리의 다른 글
| MVVM 동기 컬렉션 (0) | 2023.04.15 |
|---|---|
| Microsoft SQL Server에서 날짜만 사용하여 DATETIME 필드를 쿼리하는 방법 (0) | 2023.04.15 |
| 장고: openpyxl 워크북을 첨부 파일로 저장 (0) | 2023.04.15 |
| SQL 서버에서 INSER JOIN을 사용하여 여러 테이블에서 삭제하려면 어떻게 해야 합니까? (0) | 2023.04.15 |
| 같은 브랜치상의 2개의 다른 커밋 간에 같은 파일을 어떻게 구별합니까? (0) | 2023.04.15 |