2

I have thousands of similar files and I'd like to write their respective names after a pattern inside them. For example:

**file 1's name is nexus0000

inside the file there is:

>Pseudomonas_1M
ATGATCCGCTTCGAGCAGGTCGGCAAACGCTATC
>Pseudomonas_2M
GTGAGCTTCGAGCAGGTCGGCGAGCCGCTATC

and I want to get this:

nexus0000>Pseudomonas_1M
ATGATCCGCTTCGAGCAGGTCGGCAAACGCTATC
nexus0000>Pseudomonas_2M
GTGAGCTTCGAGCAGGTCGGCGAGCCGCTATC

**file 2's name is nexus0001

inside the file there is:

>Pseudomonas_1M
ATGATCCGCTTCGAGCAGGTCGGCAAACGCTATC
>Pseudomonas_2M
GTGAGCTTCGAGCAGGTCGGCGAGCCGCTATC

and I want to get this:

nexus0001>Pseudomonas_1M
ATGATCCGCTTCGAGCAGGTCGGCAAACGCTATC
nexus0001>Pseudomonas_2M
GTGAGCTTCGAGCAGGTCGGCGAGCCGCTATC

etc.

Up to this point, I've only managed to write the name of the file in the first line using:

for file in nexus*; do echo "$file"$"$(cat -- "$file")" > "$file"; done

Thanks for the help!

2

sed solution:

for f in nexus*; do sed -i "s/^>/$f&/" "$f"; done

Or using gawk and its inplace extension (available since v. 4.1.0):

for f in nexus*; do awk -i inplace '/^>/{ $0=FILENAME$0 }1' "$f"; done
  • I ended up using your sed solution. Worked perfectly. Many thanks! – Manuel Jul 1 '17 at 19:09
0
find . ! -name . -prune -type f -name nexus\* -exec perl -i'' -pe 's/^>/$ARGV>/' {} +

We launch a find only for the current directory, looking for regular files, names beginning with nexus and then perform an in-place editing of multiple such files by replacing the > found at the beginning of line with filename + itself.

0

This can be easily done with perl one-liner like so:

perl -i -pe 's/>/$ARGV$_/g' nexus*

Note that -i alters the file in-place, so if you want to only test the command, run it without -i flag first.

  • ITYM $& in place of $_. If there are mulitple >s in a line, the output would be ... horrendous due to that /g modifier. You could just say: perl -pi -e 's/^(?=>)/$ARGV/' nexus* – user218374 Jul 1 '17 at 11:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.