쉘 스크립트에서 하나의 하위 문자열을 다른 문자열로 교체
나는 "수지를 사랑하고 결혼한다"가 있고 "수지"를 "사라"로 바꾸고 싶다.
#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
# do something...
결과는 다음과 같아야합니다.
firstString="I love Sara and Marry"
패턴 의 첫 번째 발생을 주어진 문자열로 바꾸려면 다음을 사용하십시오 .${parameter/pattern/string}
#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
echo "${firstString/Suzi/$secondString}"
# prints 'I love Sara and Marry'
모든 항목 을 바꾸려면 다음을 사용하십시오 .${parameter//pattern/string}
message='The secret code is 12345'
echo "${message//[0-9]/X}"
# prints 'The secret code is XXXXX'
(이 설명되어 배쉬 참조 설명서 §3.5.3, "쉘 매개 변수 확장을" .)
이 기능은 POSIX에 의해 지정되지 않았습니다. 이것은 Bash 확장입니다. 따라서 모든 Unix 쉘이이를 구현하지는 않습니다. 관련 POSIX 문서는 The Open Group Technical Standard Base Specifications, Issue 7 , the Shell & Utilities volume, §2.6.2 "Parameter Expansion"을 참조하십시오 .
이것은 bash 문자열 조작으로 전적으로 수행 할 수 있습니다.
first="I love Suzy and Mary"
second="Sara"
first=${first/Suzy/$second}
첫 번째 발생 만 대체합니다. 모두 바꾸려면 첫 번째 슬래시를 두 배로 늘립니다.
first="Suzy, Suzy, Suzy"
second="Sara"
first=${first//Suzy/$second}
# first is now "Sara, Sara, Sara"
이 시도:
sed "s/Suzi/$secondString/g" <<<"$firstString"
Dash의 경우 모든 이전 게시물이 작동하지 않습니다.
POSIX sh
호환 솔루션은 다음과 같습니다.
result=$(echo "$firstString" | sed "s/Suzi/$secondString/")
sed
문자열에 RegExp 문자 가있는 경우 보다 bash를 사용하는 것이 좋습니다 .
echo ${first_string/Suzi/$second_string}
Windows에 이식 할 수 있으며 적어도 Bash 3.1만큼 오래된 버전에서 작동합니다.
탈출에 대해 많이 걱정할 필요가 없음을 보여주기 위해 다음과 같이 설정하겠습니다.
/home/name/foo/bar
이것으로 :
~/foo/bar
그러나 /home/name
처음에있는 경우에만 . 우리는 필요하지 않습니다 sed
!
bash가 우리에게 매직 변수를 제공 $PWD
하고 $HOME
, 우리는 다음을 할 수 있습니다.
echo "${PWD/#$HOME/\~}"
편집 : 인용 / 이스케이프에 대한 메모에 대한 의견에 Mark Haferkamp 에게 감사드립니다 ~
. *
변수 $HOME
에 슬래시가 포함되어 있지만 아무 것도 깨지지 않았습니다.
추가 자료 : 고급 Bash 스크립팅 가이드 .
using sed
이 필수 인 경우 모든 문자 를 이스케이프 해야합니다 .
내일 당신이 결혼을 사랑하지 않기로 결정하면 그녀도 대체 될 수 있습니다.
today=$(</tmp/lovers.txt)
tomorrow="${today//Suzi/Sara}"
echo "${tomorrow//Marry/Jesica}" > /tmp/lovers.txt
연인을 떠나는 방법은 50 가지가 틀림 없다.
댓글을 추가 할 수 없기 때문에. @ruaka 예제를 더 읽기 쉽게 만들려면 다음과 같이 작성하십시오.
full_string="I love Suzy and Mary"
search_string="Suzy"
replace_string="Sara"
my_string=${full_string/$search_string/$replace_string}
or
my_string=${full_string/Suzy/Sarah}
Pure POSIX shell method, which unlike Roman Kazanovskyi's sed
-based answer needs no external tools, just the shell's own native parameter expansions. Note that long file names are minimized so the code fits better on one line:
f="I love Suzi and Marry"
s=Sara
t=Suzi
[ "${f%$t*}" != "$f" ] && f="${f%$t*}$s${f#*$t}"
echo "$f"
Output:
I love Sara and Marry
How it works:
Remove Smallest Suffix Pattern.
"${f%$t*}"
returns "I love
" if the suffix$t
"Suzi*
" is in$f
"I love
Suzi and Marry
".But if
t=Zelda
, then"${f%$t*}"
deletes nothing, and returns the whole string "I love Suzi and Marry
".This is used to test if
$t
is in$f
with[ "${f%$t*}" != "$f" ]
which will evaluate to true if the$f
string contains "Suzi*
" and false if not.If the test returns true, construct the desired string using Remove Smallest Suffix Pattern
${f%$t*}
"I love
" and Remove Smallest Prefix Pattern${f#*$t}
"and Marry
", with the 2nd string$s
"Sara
" in between.
I know this is old but since no one mentioned about using awk:
firstString="I love Suzi and Marry"
echo $firstString | awk '{gsub("Suzi","Sara"); print}'
'your programing' 카테고리의 다른 글
어셈블리 파일 버전을 어떻게 얻을 수 있습니까? (0) | 2020.09.30 |
---|---|
Scala 대 Groovy 대 Clojure (0) | 2020.09.30 |
SQL Server에서 주어진 테이블을 참조하는 모든 외래 키를 나열하려면 어떻게해야합니까? (0) | 2020.09.30 |
애플리케이션 또는 프로세스의 실제 메모리 사용량을 측정하는 방법은 무엇입니까? (0) | 2020.09.30 |
AddTransient, AddScoped 및 AddSingleton 서비스 차이점? (0) | 2020.09.30 |