我对 `sed -i.bak '/^x /d' "$SOME_FILE"` 的解释正确吗?

我对 `sed -i.bak '/^x /d' "$SOME_FILE"` 的解释正确吗?

由于某种原因sed总是让我感到害怕,我想它的语法有点奇怪。我想确保我理解以下内容会做什么。

sed -i.bak '/^x /d' "$SOME_FILE"
  1. $SOME_FILE这将首先对${SOME_FILE}.bak( )进行备份-i.bak
  2. $SOME_FILE与正则表达式“”匹配的每一行^x(即以 ' x' 开头,后跟空格的行)将被删除。

答案1

是的,你的理解是正确的。从你的格式来看,我假设你正在使用 GNU (其他实现可能需要在和sed之间有一个空格,有些可能根本不支持)。其工作原理如下(来自):-i.bak-i-iinfo 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).

 This option implies `-s'.

 When the end of the file is reached, the temporary file is renamed
 to the output file's original name.  The extension, if supplied,
 is used to modify the name of the old file before renaming the
 temporary file, thereby making a backup copy(2)).

 This rule is followed: if the extension doesn't contain a `*',
 then it is appended to the end of the current filename as a
 suffix; if the extension does contain one or more `*' characters,
 then _each_ asterisk is replaced with the current filename.  This
 allows you to add a prefix to the backup file, instead of (or in
 addition to) a suffix, or even to place backup copies of the
 original files into another directory (provided the directory
 already exists).

 If no extension is supplied, the original file is overwritten
 without making a backup.

d命令删除前一个表达式成功的任何行。严格来讲,它删除了“模式空间”,但在简单的sed脚本中就是该行。

答案2

'/^x /d'这里不需要实际空间。更好的是'/^x\s\d'它代表字符串的开头,从x空格开始,然后是数字。

相关内容