regex - bash 脚本中使用的以下 sed 行的含义

标签 regex linux bash sed

我最近在 bash 脚本中遇到以下行

sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' | sed -e '$s/,$/\n/'

管道第一部分的输入由另一个管道给出,输入的形式为 1,2.3,2.453,23.5345,

最佳答案

表达的很到位。让我们试着把它拆开。前几个命令是

sed -e     invokes `sed` with the `-e` flag: "expression follows"
:a         a label - can be used with a branch statement (think "goto")
'/\n*$/    any number of carriage returns followed by end of string
{$d;N;ba'  delete the last line; next; branch to label a
-e '}'     close the bracket

这真的可以被认为是一个 sed 脚本文件的单行等价物:

:a         # label a 
{          # start of group of commands
/\n*$/     # select a line that has carriage returns and then end of string
           #(basically empty lines at end of file)
$d;        # delete the last line ($ = last line, d = delete)
N;         # next
ba         # branch to a
}          # end of group of commands

最后,我们在输入中没有留下空行。您可以使用末尾有空行的文件对此进行测试 - 您会发现当您通过脚本的第一部分运行它时,空行消失了。

现在让我们看看第二个(更简单的)部分:

sed -e     invoke sed on the output of the previous command
'$s        substitute in the last line
/,$/\n/    a comma before the end of the line with a newline

换句话说,整个脚本似乎是这样的:

Remove all empty lines at the end of the input, then strip the comma at the end of the last line that was not an empty line and replace it with a newline

关于regex - bash 脚本中使用的以下 sed 行的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21665522/

相关文章:

python - 从作为守护进程运行的 python 脚本中解压缩文件时出错

linux - 在linux终端中获取各种信息

javascript - 使用来自后端的 Regexp 进行 Angular 电子邮件验证

node.js - 安装了 NodeJs 但无法执行。用 bash 脚本搞砸了

javascript - 确定字符串是否至少有 2 个来自数组的相同元素

php - Laravel 5.2 - 如何通过 Modal/Controller 运行 shell 命令

bash - 意外标记附近的语法错误 'fi'

python - 传输完成后将文件移动到另一个目录

javascript - Jquery 实时替换文本不起作用

javascript - 用于测试字符串、数字和特殊字符的 javascript 正则表达式