將 sed 指令與變數一起使用

將 sed 指令與變數一起使用

我已經嘗試了 Stack Overflow 及其相關網站上提供的所有可能的解決方案,但沒有找到任何解決方案。我在這個問題上花了相當多的時間,終於發布了這個問題。

我想將sed命令與 shell 變數一起使用。我的腳本非常簡單:

## string to replace is the text after comma in the variable pc.
to_replace=${pc#*,}
echo $to_replace

##text to be replaced by the following line
replace_with="PARTITIONED BY ($pc1);"
echo $replace_with

## use sed command to replace.
sed "s@$to_replace@$replace_with@" $entry  ## $entry is the variable that contains the file name

這兩個echo命令分別給出以下輸出:

PARTITIONEDED BY (date_key );  ## the text I want to be replaced
PARTITIONED BY ( date_key int );  ## the text I want to replace with

我要么收到錯誤:

sed: -e expression #1, char 2: unterminated `s' command

或者文字根本沒有被替換。

請有人幫忙。我正在使用 Centos 6(如果有的話)。先致謝!

答案1

sed: -e expression #1, char 2: unterminated `s' command

錯誤訊息顯示錯誤發生在第二個字元上,這看起來很奇怪。我可以透過在第一個變數的開頭添加換行符來重現這一點:

$ a=$'\nfoo'
$ b='bar'
$ sed "s@$a@$b@"
sed: -e expression #1, char 2: unterminated `s' command

未轉義的換行符終止 sed 指令。當然,稍後放入換行符a會在後面的字元上產生錯誤。

您確實在腳本的前面列印了這兩個變量,但它們沒有被引用,因此它們中的任何前導空格都將被刪除,中間的空格將顯示為單個空格。

檢查變數實際包含的內容,如下所示:

printf ">%s<\n" "$to_replace"
printf "%q\n" "$to_replace"

後者是 Bash 功能,它以 Bash 接受作為輸入的方式顯示引用的字串。set -x也會顯示 sed 命令列的內容,但您需要注意其輸出中的文字換行符。

因此,如果只有一個前導換行符,您可以在腳本的開頭刪除它:

to_replace=${pc#*,}
to_replace=${to_replace#$'\n'}

(您可以將它們合併為一個,但即使換行符不存在,單獨的步驟也可以工作。)

答案2

嘗試這個

sed -i -e "s@$to_replace@$replace_with@g" "$entry"

在哪裡

  • -i意味著“就地”替換,如果不使用-i替換將在標準輸出上。

相關內容