user3489502
user3489502

Reputation: 3611

Use the paste command on file and save result to that same file

Basically I'm changing the carriage returns in my file using the paste command, but I'd like to save the result to that same file.

paste -s -d, filename1

I cannot install any tools like Sponge.

Upvotes: 1

Views: 350

Answers (1)

Allan
Allan

Reputation: 12438

If you really want to use the paste command you will have to go for an approach like this one where you use a tmp file and you replace the original one (take a backup of your file before doing this):

XXX@XXX:~/Downloads/fun_play/archive/filestosearch$ cat filename1 
abc
123
edf
xyz
XXX@XXX:~/Downloads/fun_play/archive/filestosearch$ paste -s -d, filename1 > filename2 && mv filename2 filename1
XXX@XXX:~/Downloads/fun_play/archive/filestosearch$ cat filename1 
abc,123,edf,xyz

Notes: The move operation will only take place if the paste ends up without error

If you are allowed to use other commands like sed then you can use the inline mode to modify directly the file without creating a tmp one.

XXX@XXX:~/Downloads/fun_play/archive/filestosearch$ cat filename1 
abc
123
edf
xyz
XXX@XXX:~/Downloads/fun_play/archive/filestosearch$ sed -i".bak" ':loop;N;$!bloop;s/\n/,/g' filename1 
XXX@XXX:~/Downloads/fun_play/archive/filestosearch$ cat filename1
abc,123,edf,xyz
XXX@XXX:~/Downloads/fun_play/archive/filestosearch$ cat filename1.bak 
abc
123
edf
xyz

Notes:

  • -i".bak" allow you to modify the file and to take a backup file just in case, same file name and suffix .bak
  • ':loop;N;$!bloop;s/\n/,/g' create a label loop, add each line to the pattern buffer, when not reaching the last line, go to label loop, when you reach the last line you replace all the EOL (\n) by ,.

Upvotes: 1

Related Questions