![](/img/trans.png)
[英]How to replace specific word in text with asterisks“*” equal to the word's length?
[英]Bash: Replace word with spaces equal to the length of the word
我以為我的bash-fu足夠強大,但顯然不是。 我似乎無法弄清楚這一點。 我想做這樣的事情:
var="XXXX This is a line"
word_to_replace="XXXX"
# ...do something
echo "Done:${var}"
Done: This is a line
基本上我想用空格快速替換單詞中的所有字符,最好是一步完成。 注意,如果它使事情變得更容易var
當前將在字符串的開頭,盡管它可能有前導空格(需要保留)。
在python我可能會這樣做:
>>> var="XXXX This is a line"
>>> word_to_replace="XXXX"
>>> var=var.replace(word_to_replace, ' '*len(word_to_replace))
>>> print("Done:%s" % var)
Done: This is a line
這是使用shell參數擴展和sed命令組合的一種方法。
$ var="XXXX This is a line"
$ word_to_replace="XXXX"
$ replacement=${word_to_replace//?/ }
$ sed "s/$word_to_replace/$replacement/" <<<"$var"
This is a line
?
匹配任何字符, ${var//find/replace}
執行全局替換,因此變量$replacement
與$word_to_replace
具有相同的長度,但僅由空格組成。
您可以通常的方式將結果保存到變量:
new_var=$(sed "s/$word_to_replace/$replacement/" <<<"$var")
在普通的Bash中:
如果我們知道要替換的詞:
$ line=" foo and some"
$ word=foo
$ spaces=$(printf "%*s" ${#word} "")
$ echo "${line/$word/$spaces}"
and some
如果我們不這樣做,我們可以分開選擇字符串以找到主要字詞,但這有點難看:
xxx() {
shopt -s extglob # for *( )
local line=$1
local indent=${line%%[^ ]*} # the leading spaces
line=${line##*( )} # remove the leading spaces
local tail=${line#* } # part after first space
local head=${line%% *} # part before first space...
echo "$indent${head//?/ } $tail" # replace and put back together
}
$ xxx " word on a line"
on a line
如果線上只有一個單詞, head
和tail
都設置為該單詞,那也會失敗,我們需要檢查是否有空格並分別處理這兩個案例。
我使用GNU Awk:
echo "$title" | gawk '{gsub(/./, "*"); print}'
這將用星號替換每個字符。
編輯。 綜合答案:
$ export text="FOO hello"
$ export sub="FOO"
$ export space=${sub//?/ }
$ echo "${text//$sub/$space}"
hello
使用sed
:
#!/usr/bin/env sh
word_to_replace="XXXX"
var="$word_to_replace This is a line"
echo "Done: $var"
word_to_replace=$(echo "$word_to_replace" | sed 's,., ,g')
var="$word_to_replace This is a line"
echo "Done: $var"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.