當我從 xsel 取得 xkvbd 時,為什麼它會吃換行符?

當我從 xsel 取得 xkvbd 時,為什麼它會吃換行符?

我有一個腳本,我將其分配給鍵盤快捷鍵來模擬透過中鍵單擊進行貼上:

#!/bin/bash
aa=0
for randstring in `xsel`
do
  if [[ "$randstring" =~ [ěščřžýáíéúůóťďň] ]]
  then
      xxx=`xsel|sed 's/ě/\\\[ecaron]/g' |sed 's/š/\\\[scaron]/g' |sed 's/č/\\\[ccaron] g' |sed 's/ř/\\\[rcaron]/g' |sed 's/ž/\\\[zcaron]/g' |sed 's/ý/\\\[yacute]/g' |sed 's/á/\\\[aacute]/g' |sed 's/í/\\\[iacute]/g' |sed 's/é/\\\[eacute]/g' |sed 's/ú/\\\[uacute]/g' |sed 's/ů/\\\[uring]/g'  |sed 's/ó/\\\[oacute]/g' |sed 's/ď/\\\[dcaron]/g' |sed 's/ň/\\\[ncaron]/g' |sed 's/ť/\\\[tcaron]/g'  |sed ':a;N;$!ba;s/\n/\\n/g'`
      xvkbd -text "$xxx" 2>/dev/null
      aa=1
      break
  else
    aa=0
  fi
done
if [[ $aa -eq 0 ]]
    then
        xsel | xvkbd  -file - 2>/dev/null
fi

-text當文字是捷克語(我的語言)時,我使用xvkbd,因為 xvkbd 不理解像 ě 這樣的變音符號,而只能理解像 這樣的形式\[ecaron]。現在,使用此選項,如果有換行符號 int xsel,則不會使用 xvkbd 列印它。然而,當我這樣做時

xx="---8<-----\nToday date is: $(date +%Y%m%d)\n---8<-----" 
xvkbd -text "$xx"  2>/dev/null

換行符確實會被印出。

我懷疑問題出在最後一個 sed 表達式中sed ':a;N;$!ba;s/\n/\\n/g',但我不知道該如何改進。我想我需要以某種方式照顧\ns?

答案1

編輯:我發現了這個問題,但是當你確實想要一個尾隨換行符 `... 時,其餘部分可能仍然值得閱讀。

你錯過了一個額外的\\,甚至只是一個\

  sed ':a;N;$!ba;s/\n/\\\\n/g'`  

$( )更多資訊:關於 的vs 反引號的問題 command substitution,提到了我對此問題的評論,這裡是 的摘錄man bash

When  the  old-style  backquote form of substitution is used, backslash
retains its literal meaning except when followed by $, `,  or  \.   The
first backquote not preceded by a backslash terminates the command sub‐
stitution.  When using the $(command) form, all characters between  the
parentheses make up the command; none are treated specially.

--原帖--

它不會打印最後一個\n,但會將中間添加\n$xx...

這是您上次通話的簡化版本sed

printf '%s\n' 'a\[ecaron]' b c '\[rcaron]d' |
   sed ':a;N;$!ba;s/\n/\\n/g' 

輸出:

a\[ecaron]\nb\nc\n\[rcaron]d

它沒有結尾的原因\n(在上面的範例中)是因為最後一行的模式空間中根本不會有尾隨換行符(只有來自前一個行結束符 via 的換行符N才會在那裡) ... sed隨後將在退出時輸出最終的換行符,但即便如此,它也會被xx=$(command substitution)by$( )backticks... 吞噬

要包含決賽\n,只需要最後一次換人。

sed ':a;N;$!ba;s/\n/\\n/g;s/$/\\n/'

還是說你連中間的\ns都沒有拿到?


只是附註:你不需要有無數seds呼叫那麼多進程。您可以透過;(冒號)連接它們,例如。sed 's/ě/\\\[ecaron]/g; s/š/\\\[scaron]/g; .... 或甚至不使用冒號,只需將每個替換表達式放在一個新行上..這使它們可以很好地排列...

相關內容