簡體   English   中英

sed命令僅在分為兩個步驟時才有效

[英]Sed command only works when split up into two steps

有人可以向我解釋為什么將步驟1和步驟2組合為一個sed命令不起作用:

sed -e :a -e 's/^.\{0,127\}$/& /;ta' \
-e '1,46d' -e '/Pharmacom/,+5d' -e 's/^M//g' \
-e ':a;N;$!ba;s/\n//g' -e 's/---*/\n/g' file > result

但是,將同一命令分為兩個步驟即可:

第1步:

sed -e :a -e 's/^.\{0,127\}$/& /;ta' -e '1,46d' \
-e '/Pharmacom/,+5d' -e 's/^M//g'  FILE > step

第2步:

sed -e ':a;N;$!ba;s/\n//g' -e 's/---*/\n/g' step > result

我首先將您的命令翻譯為可讀的內容,這樣我就可以理解它:

# Pad lines with spaces until 128 characters long
:a
s/^.\{0,127\}$/& /
ta

# Delete first 46 lines
1,46d

# Delete line containing 'Pharmacom' and next five lines
/Pharmacom/,+5d

# Remove carriage returns
s/^M//g

# Join rest of lines on single line
:a
N
$!ba
s/\n//g

# Replace two or more dashes with a newline
s/---*/\n/g

然后我將其簡化為有問題的部分:

# Pad lines with spaces until 128 characters long
:a
s/^.\{0,127\}$/& /
ta

# Join rest of lines on single line
:a
N
$!ba
s/\n//g

或者,在一行上:

sed ':a;s/^.\{0,127\}$/& /;ta;:a;N;$!ba;s/\n//g'

問題是您使用了兩次相同的標簽名 ,所以ta命令不會重復第一個s命令,而是跳到第二個標簽:a ,而沒有填充到128個字符,而是僅插入了一個空格。

使用兩個不同的標簽名稱可以輕松解決此問題:

sed ':a;s/^.\{0,127\}$/& /;ta;:b;N;$!bb;s/\n//g'

兩句話:

  • 在這種情況下,使用sed -e '...' -e '...'還是sed '...;...'都沒關系; 它們都視為一個命令,並且標簽名稱必須唯一。
  • 我將d命令移到腳本的開頭,或者無論如何,在您要刪除的行上,所有填充工作都沒有做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM