쉘 스크립트-변수에서 첫 번째와 마지막 따옴표 ( ") 제거
아래는 더 큰 스크립트의 쉘 스크립트 스 니펫입니다. 변수가 보유한 문자열에서 따옴표를 제거합니다. 나는 sed를 사용하여 그것을하고 있습니까, 효율적입니까? 그렇지 않다면 효율적인 방법은 무엇입니까?
#!/bin/sh
opt="\"html\\test\\\""
temp=`echo $opt | sed 's/.\(.*\)/\1/' | sed 's/\(.*\)./\1/'`
echo $temp
기본 셸 접두사 / 접미사 제거 기능을 사용하면 더 간단하고 효율적입니다.
temp="${opt%\"}"
temp="${temp#\"}"
echo "$temp"
$ {opt % \ "}는 접미사"를 제거합니다 (쉘 해석을 방지하기 위해 백 슬래시로 이스케이프 처리)
$ {temp # \ "}는 접두사"를 제거합니다 (쉘 해석을 방지하기 위해 백 슬래시로 이스케이프 처리됨)
또 다른 장점은 주변 인용 부호가있는 경우에만 주변 인용 부호를 제거한다는 것입니다.
BTW, 귀하의 솔루션은 항상 첫 번째 문자와 마지막 문자를 제거합니다 (물론 데이터를 알고 있다고 확신하지만 항상 제거하고 있는지 확인하는 것이 좋습니다).
sed 사용하기 :
echo "$opt" | sed -e 's/^"//' -e 's/"$//'
(jfgagne에 의해 표시된대로 개선 된 버전, 에코 제거)
sed -e 's/^"//' -e 's/"$//' <<<"$opt"
따라서 선행은 "없음"으로, 후행은 "없음으로 대체합니다. 동일한 호출에서 -e를 사용하여 다른 sed를 파이프하고 시작할 필요가 없으며 여러 개의 텍스트 처리가 가능합니다.
tr을 사용하여 "을 삭제하십시오.
echo "$opt" | tr -d '"'
참고 : 이렇게하면 선행 및 후행이 아닌 모든 큰 따옴표가 제거됩니다.
이렇게하면 큰 따옴표가 모두 제거됩니다.
echo "${opt//\"}"
xargs를 사용하는 간단한 방법이 있습니다 .
> echo '"quoted"' | xargs
quoted
xargs 는 명령이 제공되지 않고 입력에서 따옴표를 제거하는 경우 echo를 기본 명령으로 사용합니다 (예 : 여기 참조) .
한 번만 호출하면됩니다 sed
.
$ echo "\"html\\test\\\"" | sed 's/^"\(.*\)"$/\1/'
html\test\
가장 짧은 방법 -시도 :
echo $opt | sed "s/\"//g"
실제로 모든 "(큰 따옴표)를 제거합니다 ( opt
처음과 끝이 아닌 다른 큰 따옴표가 실제로 있습니까? 그래서 실제로는 똑같은 것입니다. ;-)).
최신 정보
https://stackoverflow.com/a/24358387/1161743의 간단하고 우아한 답변 :
BAR=$(eval echo $BAR)
에서 따옴표를 제거합니다 BAR
.
===================================================== ===========
hueybois의 답변을 바탕으로 많은 시행 착오 끝에이 기능을 생각해 냈습니다.
function stripStartAndEndQuotes {
cmd="temp=\${$1%\\\"}"
eval echo $cmd
temp="${temp#\"}"
eval echo "$1=$temp"
}
아무것도 인쇄하지 않으려면 에바를로 파이프 할 수 있습니다 /dev/null 2>&1
.
용법:
$ BAR="FOO BAR"
$ echo BAR
"FOO BAR"
$ stripStartAndEndQuotes "BAR"
$ echo BAR
FOO BAR
이것이 sed를 사용하지 않고 가장 개별적인 방법이 아닙니까?
x='"fish"'
printf " quotes: %s\nno quotes: %s\n" "$x" "${x//\"/}"
또는
echo $x
echo ${x//\"/}
산출:
quotes: "fish"
no quotes: fish
I got this from Source
Easiest solution in the bash
:
$ s='"abc"'
$ echo $s
"abc"
$ echo "${s:1:-1}"
abc
This is called Substring Expansion (see Gnu Bash Manual and search for ${parameter:offset:length}
). In this example it takes the substring from s
starting at position 1 and ending at the second last position. This is due to the fact that if length
is a negative value it is interpreted as a backwards running offset from the end of parameter
.
My version
strip_quotes() {
while [[ $# -gt 0 ]]; do
local value=${!1}
local len=${#value}
[[ ${value:0:1} == \" && ${value:$len-1:1} == \" ]] && declare -g $1="${value:1:$len-2}"
shift
done
}
The function accepts variable name(s) and strips quotes in place. It only strips a matching pair of leading and trailing quotes. It doesn't check if the trailing quote is escaped (preceded by \
which is not itself escaped).
In my experience, general-purpose string utility functions like this (I have a library of them) are most efficient when manipulating the strings directly, not using any pattern matching and especially not creating any sub-shells, or calling any external tools such as sed
, awk
or grep
.
var1="\"test \\ \" end \""
var2=test
var3=\"test
var4=test\"
echo before:
for i in var{1,2,3,4}; do
echo $i="${!i}"
done
strip_quotes var{1,2,3,4}
echo
echo after:
for i in var{1,2,3,4}; do
echo $i="${!i}"
done
참고URL : https://stackoverflow.com/questions/9733338/shell-script-remove-first-and-last-quote-from-a-variable
'IT story' 카테고리의 다른 글
정렬 된 목록은 CSS로 1.1, 1.2, 1.3 (1, 2, 3 대신 ...)과 같은 결과를 생성 할 수 있습니까? (0) | 2020.05.19 |
---|---|
앱 (22.0.0) 및 테스트 앱 (21.0.3)의 해결 된 버전이 다릅니다. (0) | 2020.05.19 |
데이터베이스, 테이블, 열의 데이터 정렬을 변경하는 방법은 무엇입니까? (0) | 2020.05.19 |
신속한 언어 구조와 클래스 (0) | 2020.05.19 |
Android에서 네트워크 연결 유형 감지 (0) | 2020.05.19 |