如何僅刪除位於指定行號且與模式相符的行?
例如:
- 我想要刪除(
d
); - 這第三線 (
3
); - 如果它是空白的(
^$
);
文法如下:
cat file | sed '3 /^$/d'
傳回以下錯誤:
sed: -e expression #1, char 3: unknown command: `/'
答案1
嘗試這樣做:
sed '3{/^$/d;}' file
注意大括號。
答案2
就像 user000001 回答的那樣,sed '3{/^$/d;}' file
已經足夠好了,但它只會向您顯示該輸出。如果你想修改該文件,並且你的系統sed
是GNU sed
,則可以使用sed -i '3{/^$/d}' file
(對於GNU sed
,這裡;
前面的}
也可以省略)。
`-i[SUFFIX]' `--in-place[=SUFFIX]' This option specifies that files are to be edited in-place. GNU `sed' does this by creating a temporary file and sending output to this file rather than to the standard output.(1).
對於 FreeBSD/OS/X sed
,請使用sed -i '' '3{/^$/d;}' file
.