Home > Back-end >  Bash; Replacing new line with ", " and ending with ".", can someone explain awk
Bash; Replacing new line with ", " and ending with ".", can someone explain awk

Time:08-31

so let's say i have

aaa
bbb
ccc
ddd

and i need to replace all new lines by comma and space, and end with a dot like so

aaa, bbb, ccc, ddd.

I found this, but i can't understand it at all and i need to know what every single character does ;

... | awk '{ printf $0", " }' | sed 's/.\{2\}$/./'

Can someone make those two commands human-readable ? tysm!

CodePudding user response:

About the command:

... | awk '{ printf $0", " }' | sed 's/.\{2\}$/./'

Awk prints the line $0 followed by , without newlines. When this is done, you have , trailing at the end.

Then the pipe to sed replaces the last , with a single dot as this part .\{2\}$ matches 2 times any character at the end of the string.


With sed using a single command, you can read all lines using N to pull the next line in the pattern space, and use a label to keep on replacing a newline as long as it is not the last line last line.

After that you can append a dot to the end.

sed ':a;N;$!ba;s/\n/, /g;s/$/./' file

Output

aaa, bbb, ccc, ddd.

CodePudding user response:

echo 'aaa
bbb
ccc
ddd' | 

mawk NF =RS FS='\412' RS= OFS='\40\454' ORS='\456\12'
aaa, bbb, ccc, ddd.
  • Related