微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

regex – 跟随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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐