Reputation: 2564
I want to replace new line char(\n) with ','
(along with starting and closing single quotes) in shell script by using tr
command. But tr
command is not replacing char correctly
Here is the command i used:
< 1.txt tr "\n" "','"
Output for this command :
erer'erer.'erer'erer'
File 1.txt is like :
erer
erer.
erer
erer
Please suggest me how this can be done using the same command.
Question Edited
Upvotes: 2
Views: 10107
Reputation: 6239
tr
is only to transliterate characters. You could do:
$ seq 10 | sed "s/.*/'&'/" | paste -sd, -
'1','2','3','4','5','6','7','8','9','10'
Or if you don't want the first and last '
:
$ seq 10 | sed '$!G;$!G' | paste -sd "','" -
1','2','3','4','5','6','7','8','9','10
Upvotes: 2
Reputation: 785611
tr is not the right tool for this since tr does char by char translation instead of char to a string replacement. use awk:
awk '{printf("'"'"'%s'"'"',", $0)} END{print ""}' 1.txt
To avoid all weird double quote/single quote stuff use:
awk '{printf("\x27%s\x27,", $0)} END{print ""}' 1.txt
To avoid printing comma after last line:
awk '{a[cnt++]=$0} END{ for (i=0; i<length(a)-1; i++) printf("\x27%s\x27,", a[i]);
print a[i]}' 1.txt
Upvotes: 3