Meaning of the following sed lines used in a bash script

I recently met the following line in a bash script

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

the input to the first part of the pipe is defined by another pipeline, and the entrance has the form 1,2.3,2.453,23.5345,

+3
source share
2 answers

Pretty expression. Let's try to parse it. The first few teams:

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

It really can be seen as the one-line equivalent of a sed script file:

: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

at the end of this we have no empty lines in the input. You can test this with a file with empty lines at the end - you will find that when you ran it through this first part of the script, the empty lines disappeared.

Now let's look at the second (simpler) bit:

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

In other words, everything seems to be script:

, , ,

+6

: , . awk script sed script /.

, @Floris , script, GNU awk. , :

$ cat file
1,2.3,2.453,23.5345,
1,2.3,2.453,23.5345,


$
$ gawk -v RS=',\n+$' '{print}' file
1,2.3,2.453,23.5345,
1,2.3,2.453,23.5345
$

RS=',\n+$' awk, 1 , 1 . {print} , '1' , , , , OP awk.

+4

All Articles