문자열에서 특수 문자를 이스케이프 처리하는 방법은 무엇입니까? $file제거하지 않고 작은 따옴표와 다른 특수 문자를

$file파일 이름의 값을 보유 한다고 가정 하십시오 Dr' A.tif. bash 프로그래밍에서 특수 문자를 $file제거하지 않고 작은 따옴표와 다른 특수 문자를 어떻게 벗어날 수 있습니까?

2014 년 7 월 9 일 업데이트

@Gilles에서 요청을 처리 할 수있게하지 않는 코드에 따라 Dr' A.tif:

files=$(find /path/ -maxdepth 1 -name "*.[Pp][Dd][Ff]" -o -name "*.[Tt][Ii][Ff]")
echo "${files}" > ${TEMP_FILE}
while read file
do
   newfile=$(echo "${file}" | sed 's, ,\\ ,g') ## line 1
done < ${TEMP_FILE}

@Patrick on 에서 답을 시도한 후에는 line 1효과가있는 것 같습니다. 하지만이 같은 파일이있는 경우 Dr\^s A.tif, printf명령 도움이하지 않는 것, 그것은 나를 보여줍니다 Dr\^s\ A.tif. 다음과 같이 콘솔에서 수동으로 시도하면 :

printf "%q" "Dr\^s A.tif"

나는이 출력을 가질 것이다 :

Dr\\\^s\ A.tif

이것을 처리하는 방법에 대한 아이디어가 있습니까?



답변

printf내장 기능을 사용 %q하여이를 수행 할 수 있습니다 . 예를 들면 다음과 같습니다.

$ file="Dr' A.tif"
$ printf '%q\n' "$file"
Dr\'\ A.tif

$ file=' foo$bar\baz`'
$ printf '%q\n' "$file"
\ foo\$bar\\baz\`

bash 문서에서 printf:

In addition to the standard format specifications described in printf(1)
and printf(3), printf interprets:

 %b       expand backslash escape sequences in the corresponding argument
 %q       quote the argument in a way that can be reused as shell input
 %(fmt)T  output the date-time string resulting from using FMT as a format
          string for strftime(3)

답변

시험:-

file=Dr\'\ A.tif
echo $file
Dr' A.tif

또는

file="Dr' A.tif"
echo $file
Dr' A.tif

또는 문자열에 큰 따옴표가 포함 된 경우 :-

file='Dr" A.tif'
echo $file
Dr" A.tif

인터넷에서 이스케이프 및 인용에 대한 좋은 자습서가 있습니다. 시작 이 하나 .


답변

스크립트에서 처리중인 파일 이름을 이스케이프 처리하지 않아도됩니다. 이스케이프는 파일 이름을 스크립트에 리터럴 로 넣거나 여러 파일 이름을 단일 입력 스트림으로 다른 스크립트에 전달 하려는 경우에만 필요합니다 .

당신의 출력을 통해 반복하고 있기 때문에 find, (!) 가장 간단한 방법 중 하나입니다 가능한 모든 경로를 처리 :

while IFS= read -r -d ''
do
    file_namex="$(basename -- "$REPLY"; echo x)"
    file_name="${file_namex%$'\nx'}"
    do_something -- "$file_name"
done <(find "$some_path" -exec printf '%s\0' {} +)


답변

빠르고 (매우) 더러운

find . | sed 's/^/"/' | sed 's/$/"/'


답변

가장 많이 사용되는 답변을 포함하여 이러한 답변 printf "%q"은 추가 조작없이 모든 경우에 작동하지 않습니다. 다음을 제안합니다 (아래 예).


cat <<EOF;
2015-11-07T03:34:41Z app[postgres.0000]: [TAG] text-search query doesn't contain lexemes: ""
EOF


답변