2017-11-30 2 views
0

질문은 다음과 같습니다. 텍스트의 각 줄에서 문자를 표시하십시오.잘라 내기 명령으로 공백을 무시하십시오

while read line 
do 
    a=`echo $line | cut -c 2` 
    b=`echo $line | cut -c 7` 

    echo -n $a 
    echo $b 
done 

문제는 첫 번째 문자가 공백 인 경우,이 공간을 인쇄하지 않는다는 것입니다 :

내 코드이었다. 예 :

Input: 
A big elephant 

Expected output: 
e 

My output: 
e 

어떻게 고칠 수 있습니까?

답변

1

간단한 변화 : bash + cut로 ---

s="A big elephant" 
echo "${s:1:1}${s:8:1}" 
e 

:

순수 bash ( 조각에 내놓고)와

---

s="A big elephant" 
cut -c 2,7 <<<"$s" 
e 
0

나는 그것을 해결 한 너무

while read line 
do 
    a=`echo $line | cut -c 2` 
    b=`echo $line | cut -c 7`  
echo "$a$b" 
done 
3

당신은 변수를 인용 할 필요가있다. bash가 $ a를 확장 할 때 공백은 인수로 표시되지 않으므로 echo로 인쇄되지 않습니다.

명령에는 많은 공백이있을 수 있지만 bash는 기본적으로 명령과 인수를 구분하기 위해 공백을 사용하기 때문에 명시 적으로 인수의 일부 (따옴표 또는 이스케이프 사용)가 아니면 여분의 공백이 무시됩니다.

예를 들어

:

=> touch file 1  # Makes two files: "file" and "1" 
=> touch "file 1" # Makes one file: "file 1" 
=> touch file\ 1  # Makes one file: "file 1" 

귀하의 최종 코드는 다음과 같습니다 :

while read line 
do 
    a=`echo $line | cut -c 2` 
    b=`echo $line | cut -c 7` 

    echo -n "$a" 
    echo "$b" 
done 
그들이 인용되지 않는 공간, 파일 이름에서 탈출해야하는 이유

=> echo a  # Argument without spaces works (at least in this case) 
a 
=> echo a  # Two spaces between, unquoted spaces are ignored 
a 
=> echo " a" # Quotes make the space part of the argument 
a 
=> echo  a # Arguments can have many spaces between them 
a 
=> echo   # No quotes or spaces, echo sees no arguments, doesn't print anything 

=> echo " "  # Space is printed (changed to an underscore, wouldn't actually be visible) 
_ 
=> 

이 또한