Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change "-" to "C" in all files within directory

I have some files that looks like this:

---HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH--HHHHHHHHHHHHHHHHHHHHHHHHHH------HHHHHHHHHHHHHHHHHHHHHHH-----HHHHHHHHHHHHHHHHHHH-
d2qupa_.dssp (END)

And I would like to change all those with "-" to "C"

This is a file in a directory of 150 files that are similar, so I need a code that applies to every files.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried this:

for f in *.dssp; do mv -- "$f" "${f//"-"/"C"}"; done

It does not work at all, no error, even though its clearly parsing the files.

Is it because it is a directory that its not opening the file itself and applying the loop?

>Solution :

I think you are conflating the file name with the file contents

This:

for f in *.dssp; do mv -- "$f" "${f//"-"/"C"}"; done

seems to be using mv which is trying to rename the file. Instead, you example is addressing the file contents.

To change the contents as in your example, you only need sed.

Given:

$ head *.dssp
==> f1.dssp <==
---HHHHHHHHHHHHHHHHHHHHHHH--HHHHHHHHH--HHHHHHHHHHHHHHHHHHHHHHHHHH------HHHHHHH--HHHHHHHHHHHHHH-----HHHHHHHHHHHHHHHHHHH-
d2qupa_.dssp (END)

==> f2.dssp <==
---HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH--HHHHHHHHHHHHHHHHHHHHHHHHHH------HHHHHHHHHHHHHHHHHHHHHHH-----HHHHHHHHHHHHHHHHHHH-
d2qupa_.dssp (END)

You can use sed to modify all files in place (the original files are saved with .old extension):

$ sed -i .old 's/-/C/g' *.dssp

$ head *.dssp
==> f1.dssp <==
CCCHHHHHHHHHHHHHHHHHHHHHHHCCHHHHHHHHHCCHHHHHHHHHHHHHHHHHHHHHHHHHHCCCCCCHHHHHHHCCHHHHHHHHHHHHHHCCCCCHHHHHHHHHHHHHHHHHHHC
d2qupa_.dssp (END)

==> f2.dssp <==
CCCHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHCCHHHHHHHHHHHHHHHHHHHHHHHHHHCCCCCCHHHHHHHHHHHHHHHHHHHHHHHCCCCCHHHHHHHHHHHHHHHHHHHC
d2qupa_.dssp (END)

From your comment above:

I tried this: for f in *.dssp; do sed 's/-/C/g' ; done it just leaves the command line hanging That is because sed is waiting for a file in that shell loop.

You would do for f in *.dssp; do sed -i .bak 's/-/C/g' "$f"; done if you want the shell to handle the glob. BUT, sed itself can handle the glob. You would want to use the shell if additional processing is required to each file. Otherwise just use sed

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading