백슬래시 이스케이프 시퀀스로 생성될 수 있는 모든 문자를 해당 이스케이프 시퀀스로 바꿉니다.

백슬래시 이스케이프 시퀀스로 생성될 수 있는 모든 문자를 해당 이스케이프 시퀀스로 바꿉니다.

편집: 처음에 요청을 명확하게 하지 않아서 죄송합니다. 실제로 백슬래시 이스케이프 방식으로 작성된 문자열에 액세스할 수 없으며 더 명확하게 만들기 위해 예제를 수정했습니다. 지금 얻은 두 가지 답변에서는 문자열에 백슬래시를 먼저 포함해야 하지만 그렇지 않습니다.

어려운 문자가 많이 포함될 수 있는 문자열이 있는데 큰따옴표 등으로 입력하면 동일한 문자열이 생성되도록 이스케이프 방식으로 파일에 쓰고 싶습니다. 및 Perl의 기능을 사용해 보았지만 echo -e해당 참조가 다릅니다.perlshell-quotequotemeta

예:

# I have a file containing difficult characters:
$ cat text
line0'field0
line1   field1"
$ cat -v text
line0'field0
line1   field1"

큰따옴표를 포함한 예상 원시 출력:

"line0'field0\nline1\tfield1\""

이미 내장된 솔루션이 있을 것이라고 확신합니다.

답변1

수정된 문구에 답장하기

마음에 떠오르는(그리고 널리 사용되는) 유일한 도구는 이지만 sed정확히 예쁘지는 않습니다.

sed ':a;N;$!ba;s/\n/\\n/g;s/\t/\\t/g'

그래서...

$ cat file
line0'field0
line1   field1"
$ sed ':a;N;$!ba;s/\n/\\n/g;s/\t/\\t/g' file
line0'field0\nline1\tfield1"  

감사의 말씀:https://stackoverflow.com/questions/1251999/how-can-i-replace-a-newline-n-using-sed

원래 진술에 답장

질문을 올바르게 이해했다면 귀하는 다음과 같은 것을 찾고 있다고 생각합니다(이것은 bash에 있습니다.}:

$ doublequoted="line0'field0\nline1\tfield1\""
$ foo="$(echo -e "${doublequoted//\\/\\\\}")"
$ echo $foo
line0'field0\nline1\tfield1"

제가 잘못 이해했다면, 무엇을 찾고 있는지 명확히 해주세요.

답변2

Bash의 경우 내장 을 사용할 수 있습니다 . 문자 printf에 주의하세요 .%

doublequoted="line0'field0\nline1\tfield1\"%s"
printf -v interpreted "${doublequoted//%/%%}"

그 다음에

$ declare -p doublequoted interpreted
declare -- doublequoted="line0'field0\\nline1\\tfield1\"%s"
declare -- interpreted="line0'field0
line1   field1\"%s"

$ printf "%s" "$interpreted" | od -c
0000000   l   i   n   e   0   '   f   i   e   l   d   0  \n   l   i   n
0000020   e   1  \t   f   i   e   l   d   1   "   %   s
0000034

업데이트된 요구 사항에 맞게 편집됨

$ cat text
line0'field0
line1   field1"

$ cat -A text           # show tabs
line0'field0$
line1^Ifield1"$

$ contents=$(< text)    # slurp the file contents into a var

$ printf -v escaped '%q' "$contents"    # "shell-escape" it

$ echo "$escaped"                       # it's in ANSI-C quoted form
$'line0\'field0\nline1\tfield1"'

$ echo "${escaped#$}"                   # output as requested
'line0\'field0\nline1\tfield1"'

관련 정보