2017-12-03 205 views
-4

空白的所有發生的最好的方式,我有一個像的Unix shell - 替換字符串

'abc', '<<some string with space>>', 'xyz' 

字符串我希望得到一個字符串象下面這樣: -

'abc', '<<some_string_with_space>>', 'xyz' 
+1

換行符是一個空格 - 您的引用字符串是否可以包含換行符?它可以包含轉義引號('\''或'''')嗎?它可以包含逗號?你能有一個空的領域嗎?目標字符串**真**總是以'<<開始並以'>>'結尾?花費一些精力來提供簡潔,可測試的示例輸入和預期的輸出,以覆蓋您的所有用例,因此我們不會根據您的需求進行猜測。 –

回答

0

只需使用awk

s="'abc', '<<some string with space>>', 'xyz'" 
awk -F', ' '{ gsub(/[[:space:]]+/,"_",$2) }1' OFS=', ' <<<"$s" 

輸出:

'abc', '<<some_string_with_space>>', 'xyz' 
+0

's =「'hello,world'」'? –

+0

@RomanPerekhrest,當字符串在','之間沒有空白時它不起作用。 s =「'abc','<<一些帶空格的字符串>>','xyz'」 –

+0

@gniourf_gniourf,怎麼樣來詳細說明所有可能的輸入?我們有一個具體的案例 – RomanPerekhrest

-1

使用awk的gsub和正則表達式\ s來替換空格字符。

mystr = "my sentence is this!" 
gsub(/\s/,"_",mystr) 
print mystr 
+0

我沒有downvote,但你應該提到那只是'\ s'的GNU awk - 你需要其他awk' [[:space:]]''。 –

0

如果你的問題涉及更換空間的廣義問題_裏面只有單引號字符串'...'而不是在其他地方, 我想解決這個使用Perl,按照這樣的邏輯:

  • 對於輸入的每個'...'(使用正則表達式:'[^']+'
  • 執行替換所有空間用_
  • 的函數

像這樣:

echo "'abc', '<<some string with space>>', 'xyz'" |\ 
    perl -pe 'sub r { $_ = @_[0]; s/ +/_/g; return $_; }; s/'"'[^']+'"'/r($&)/ge' 
1

您可以使用SED太

echo "'abc', '<<some string with space>>', 'xyz'" | sed s'/ /_/g;s/,_/, /g' 
+0

'echo「'hello,world'」|怎麼樣? sed s'//_/g; s /,_ /,/ g''? –

+0

@gniourf_gniourf,是的,你說得對,如果它總是在<< ... >>,我們可以使用sed -E':A; s /(<[^] *)()([^,] *,)/ \ 1_ \ 3 /; TA」 –

0

這可能爲你工作(GNU SED):

sed ":a;s/^\(\('[^']*',\s*\)*'[^' ]*\) /\1_/;ta" file 

或許更安全:

sed ':a;s/^\(\('\''[^'\'']*'\'',\s*\)*'\''[^'\'' ]*\) /\1_/;ta' file