Saturday, March 12, 2022

[SOLVED] Insert comma before a specific word in .txt in bash

Issue

I have text file and it has content like this,

40 number of cpu
50 number of errors

and I need to insert comma between number and words. Its should be like this,

 40, number of cpu
 50, number of errors

Solution

Put comma after the first word in a line:

sed -E 's/^[[:space:]]*[^[:space:]]+/&,/' file.txt

Put comma after the first word in a line, only if it's numeric:

sed -E 's/(^[[:space:]]*[0-9]+)([[:space:]]|$)/\1,\2/' file.txt

Put comma after every numeric field:

sed -E 's/(^|[[:space:]])([[:digit:]]+)($|[[:space:]])/\1\2,\3/g' file.txt


Answered By - dan
Answer Checked By - Candace Johnson (WPSolving Volunteer)