Performing regular expression capture and then replacing with SED / PERL

I have data that looks like this (let this submit.txt file):

 dir1/pmid_5409464.txt dir1/pmid_5788247.txt dir1/pmid_4971884.txt 

What I want to do is modify the regexp of the embedded file so that it will result in the following

 perl mycode.pl /home/neversaint/dir1/pmid_5409464.txt > /home/neversaint/dir1/pmid_5409464.output perl mycode.pl/home/neversaint/dir1/pmid_5788247.txt > /home/neversaint/dir1/pmid_5788247.output perl mycode.pl /home/neversaint/dir1/pmid_4971884.txt > /home/neversaint/dir1/pmid_4971884.output 

Is there one SED / Perl slot for this?

My difficulty is to capture the input file name, and then create an output file ( .output ) - for each line - based on this. I am stuck on this:

 sed 's/^/perl mycode.pl \/home\/neversaint\/dir1\//g' submit.txt | sed 's/$/ >/' 
+6
source share
3 answers

You can use beveled brackets to capture groups and access groups using \ 1, \ 2, etc.

 sed 's/^\(.*\).txt$/perl mycode.pl \/home\/neversaint\/\1\.txt > \/home\/neversaint\/\1.output/' submit.sh 

output:

 perl mycode.pl /home/neversaint/dir1/pmid_5409464.txt > /home/neversaint/dir1/pmid_5409464.output perl mycode.pl /home/neversaint/dir1/pmid_5788247.txt > /home/neversaint/dir1/pmid_5788247.output perl mycode.pl /home/neversaint/dir1/pmid_4971884.txt > /home/neversaint/dir1/pmid_4971884.output 

edit: it doesn't seem like sed has built-in file editing in place (GNU sed has the -i option). It is still possible, but this solution simply prints to the standard. You can also use one Perl liner as shown here: sed edit file in place

+12
source

You asked for a one-way sed, you got it.

sed 's/\([^.]*\)\.txt/perl mycode.pl \/home\/neversaint\/\1.txt > \/home\/neversaint\/\1.output/' submit.txt > output.txt

+1
source

Perl oneliner in order to do the same,

 perl -pe " s@ (.*?)(\.txt)@perl mycode.pl /home/neversaint/\\1\\2 > /home/neversaint/\\ 1.output@g " submit.txt 

The above command will create a replaced line in the console, and you will have to redirect the output to another file.

To replace in a file (built-in replacement), you can add the -i option. For instance,

 perl -pe " s@ (.*?)(.txt)@perl mycode.pl /home/neversaint/\1\2 > /home/neversaint/\ 1.output@g " -i submit.txt 

The above will do the replacement in the submit.txt file.

0
source

Source: https://habr.com/ru/post/950679/


All Articles