2017-01-19 1 views
1

저는 대학에서 배쉬를 가르치기위한 입문 과정을 진행하고 있으며 컬을 사용하여 API에서 잡힌 json 객체를 사용하는 약간의 Motd 스크립트 작업을하고 있습니다..bash의 색인에 줄 바꿈 문자를 삽입하십시오.

나는 이것이 이 아니고이 아니라는 것을 이해하고 싶습니다.하지만 배쉬로 스크립트하는 법에 대해 더 알고 싶습니다.

저는 매우 간단하게 문제가 될 수있는 것으로 갇혀 있음을 발견했습니다. 내 json-object의 'quote'값이 너무 길면 (인덱스 80에서는이 경우) 특정 줄에 새로운 줄 ('\n')을 삽입하고 싶습니다.

나는 SO 스레드의 무리를 다음 봤는데 이건 내 현재의 솔루션입니다 : 내가 echo이있는 경우 반면

#!/bin/bash 

json_object=$(curl -s 'http://quotes.stormconsultancy.co.uk/random.json') 
quote=$(echo ${json_object} | jq .quote | sed -e 's/^"//' -e 's/"$//') 
author=$(echo ${json_object} | jq .author) 
count=${#quote} 
echo $quote 
echo $author 
echo "wc: $count" 


if((count > 80)); 
then 
     quote=${quote:0:80}\n${quote:80:(count - 80)} 
else 
     echo "lower" 
fi 
printf "$quote" 

나는 printf로부터받은 전류 출력은 인용의 첫 번째 단어가있다 문자열 조작을 시도하기 전에 전체 인용문을 얻습니다.

모범 사례 또는 기타 사항을 따르지 않는 경우 유감이지만 저는 vibash을 모두 사용하는 절대 초보자입니다.

나는 모든 종류의 조언에 매우 만족할 것입니다. :)

는 편집이 :

는 샘플 출력 :

은 $ ./json.bash

은 당신의 이름있는 당신은 동일한 치료를 사용하여 변수 이름을 지정해야

은 맏아들 어린이.

"제임스 O. Coplien"높은

86

당신은 당신이 처음 태어난 nchild 이름있는 동일한 치료를 사용하여 변수의 이름을 지정해야합니다.

+0

당신은을 제공해야 모든 변수들의 샘플 출력, 당신을 위해 문제를 해결할 다른 방법은 무엇입니까? 무엇보다도 JSON 출력. 각 단계에 대한 적절한 데이터를 설명하면서 왜이 일을하고 있는지, 그리고 예상했던 일을 설명하십시오. – Inian

+0

... 또한 'bash'의 모든 변수를 큰 따옴표로 묶는 것이 좋습니다. – Inian

+0

샘플 출력을 추가했습니다. 컨텍스트에 관계없이 double on 변수를 사용합니까? 'if'처럼? – geostocker

답변

2

당신은 입력 라인 한 줄 미만의 80 charaacters

string="You should name a variable using the same care" 
(("${#string}" > 80)) && printf "%s\n" "${string:0:80}"$'\n'"${string:80}" || printf "%s\n" "$string" 
You should name a variable using the same care 

에 대한 설명

을,이를 달성하기 bash 명령을
string="You should name a variable using the same care with which you name a first-born child." 
(("${#string}" > 80)) && printf "%s\n" "${string:0:80}"$'\n'"${string:80}" || printf "%s\n" "$string" 
You should name a variable using the same care with which you name a first-born 
child. 

(과)를 사용할 수 있습니다

(("${#string}" > 80)) && printf "%s\n" "${string:0:80}"$'\n'"${string:80}" || printf "%s\n" "$string" 

# The syntax is a indirect implementation of ternary operator as bash doesn't 
# directly support it. 
# 
# (("${#string}" > 80)) will return a success/fail depending upon the length 
# of the string variable and if it is greater than 80, the command after && is 
# executed and if it fails the command after || is executed 
# 
# "${string:0:80}"$'\n'"${string:80}" 
# A parameter expansion syntax for sub-string extraction. 
# 
# ${PARAMETER:OFFSET} 
# 
# ${PARAMETER:OFFSET:LENGTH} 
# 
# This one can expand only a part of a parameter's value, given a position 
# to start and maybe a length. If LENGTH is omitted, the parameter will be 
# expanded up to the end of the string. If LENGTH is negative, it's taken as 
# a second offset into the string, counting from the end of the string. 
# 
# So in our example we basically extract the characters from position 0 to 80 
# insert a new-line and append the rest of the string 
# 
# The $'\n' syntax allows to include all escape sequence characters be 
# included, in this case just the new line character. 
+0

답변 해 주셔서 감사합니다. 솔루션에서 진행되는 작업에 대한 설명을 추가 하시겠습니까? – geostocker

+0

@geostocker : 지금 추가하십시오. 이게 네가하려는 의도 야? – Inian

0

정말 원래의 질문에,하지만 일부 추가 코드를 추가하면 단어의 중간에 중단하지 않을 수 있도록 좋은 대답을 @Inian 아니라 ${string:0:80}의 마지막 공백을합니다 :

#!/usr/bin/env bash 

string="You should really name a variable using the same care with which you name a first-born child." 
if (("${#string}" > 80)); then 
    maxstring="${string:0:80}" 
    lastspace="${maxstring##*\ }" 
    breakat="$((${#maxstring} - ${#lastspace}))" 
    printf "%s\n" $"${string:0:${breakat}}"$'\n'"${string:${breakat}}" 
else 
    printf "%s\n" "$string" 
fi 

maxstring=${string:0:80} :

따옴표의 처음 80자를 봅시다.

lastspace=${maxstring##*\ }

:

$maxstring의 전면에서 (이스케이프 공백) *\의 가장 긴 일치를 삭제는 ${lastspace}는 문자열의 마지막까지 마지막 공백에서 나머지 문자열입니다.

breakat="$((${#maxstring} - ${#lastspace}))"

:

${maxstring}에서 공백의 마지막 인덱스를 얻을 수 ${maxstring}의 길이 ${lastspace}의 길이를 뺍니다. 이것은 \n이 삽입 될 색인입니다. 문자 80에서 가장 가까운 공백에서 "소프트"휴식과

You should really name a variable using the same care with which you name a firs 
t-born child. 

예 출력 : 문자 80에서 "하드"휴식과

예 출력

You should really name a variable using the same care with which you name a 
first-born child. 
관련 문제