我最近在 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/