Text edit off-the-wall question

Chat about Linux in general
Post Reply
User avatar
MikeLieberman
Level 1
Level 1
Posts: 36
Joined: Thu Apr 28, 2016 8:41 am
Location: Philippines
Contact:

Text edit off-the-wall question

Post by MikeLieberman » Wed Jul 11, 2018 9:37 am

Is there a command I can issue to test for a value/condition in a text file and if the condition is met to alter the text.

Here's an example. Scattered in 500+ files there are places where the phrase:
So,
is not followed by a [space] but some other character. However there are also places in those files where there is:
So,[space]

I need to test for the condition were [space] does not follow the comma and add a space in all those files holding an aggregate more that 50 megabytes of text.

Can this be done?

User avatar
xenopeek
Level 24
Level 24
Posts: 22497
Joined: Wed Jul 06, 2011 3:58 am
Location: The Netherlands

Re: Text edit off-the-wall question

Post by xenopeek » Wed Jul 11, 2018 9:47 am

Sure, with sed. With below command it does the following:
- find a comma that is not followed by a space
- insert a comma after that space and before the character following it

The basic command to test this is as follows (it won't make changes to the file yet):
sed -r 's/,([^[:space:]])/, \1/g' filename
Replace filename with the name of the file to test with in the current directory (you can use Tab key on the terminal to auto-complete partially typed filenames).

Or to save the output in another file so you can study the results:
sed -r 's/,([^[:space:]])/, \1/g' filename > newfilename

If you've confirmed it indeed does what you need you can add the -i option to make it actually write the changes to the file:
sed -r -i 's/,([^[:space:]])/, \1/g' filename

Sed can work on multiple files so you can replace filename in above with * to process all the files in the current directory for example. Or *.txt for all files with .txt extension. If you need more help share some more detail as to how you've organized the files.
Image

User avatar
MikeLieberman
Level 1
Level 1
Posts: 36
Joined: Thu Apr 28, 2016 8:41 am
Location: Philippines
Contact:

Re: Text edit off-the-wall question

Post by MikeLieberman » Wed Jul 11, 2018 11:23 am

Thanks!

Post Reply

Return to “Chat about Linux”