There is lots of good answers using sed
or awk
here, which are perfectly fine to do that (even better than the following one). But just for fun, here is a bash
only solution (without needing to invoke external programs like grep
or whatever) which also do the trick:
$ while read -r; do p=""; [[ ! $REPLY =~ [^,]*\,[^,]* ]] && p=" ,"; echo "${p}${REPLY}"; done < test.txt
name,path:A:B
,loc:D
name,for:B:C
The explained version:
#!/bin/bash
while read -r; do # looping over a file the right way in bash
p="" # initializing a prefix
[[ ! $REPLY =~ [^,]*\,[^,]* ]] && p=" ," # if the line doesn't contain a comma, the prefix will contain a comma
echo "${p}${REPLY}"; # print the line with the prefix which can be blank or not
done < test.txt