Xterra
December 8, 2017, 2:23pm
1
I have a bunch of text files like this:
Sample_S1_L001_R1.txt
Sample_S10_L001_R1.txt
Sample_S11_L001_R1.txt
I am using the following script to add a 0
to those files with a single digit after the S
:
ls *.txt | sed 's/\(.*_S\)\([1-9]_.*\)/mv & \10\2/' | sh
And then the following script to move and replace the SXX
to the beginning of the file name:
ls *.txt | sed 's/\(.*_\)\(S\)\([0-9]*_\)\(.*\)/mv & MID-\3\1\4/' | sh
I am actually generating the desired output:
MID-01_Sample_L001_R1.txt
MID-10_Sample_L001_R1.txt
MID-11_Sample_L001_R1.txt
I just think that should be a way to modify my second script so I can accomplish the same task
Any help will be greatly appreciated
RudiC
December 8, 2017, 2:41pm
2
Hmmm - I wildly guess you want to
correct the first script to run error free
combine the two into one single script
?
EDIT: Try
ls *.txt | sed -r 'h; s/(.*_S)([1-9]_.*)/\10\2/; s/^(.*_)S([0-9]{2}_)/ MID-\2\1/; H; g; s/\n//; s/^/mv /'
and pipe through sh
if happy with what you get.
Another solution.
The substitution for the two digit is straight forward;
a second substitution cares about the one digit.
ls *.txt | sed '
s/\(.*_\)S\([0-9][0-9]_\)\(.*\)/mv & MID-\2\1\3/
s/\(.*_\)S\([0-9]_\)\(.*\)/mv & MID-0\2\1\3/
'
You can put a t
command after the first substitution, then, if successful, the second substitution will be skipped.
ls *.txt | sed '
s/\(.*_\)S\([0-9][0-9]_\)\(.*\)/mv & MID-\2\1\3/
t
s/\(.*_\)S\([0-9]_\)\(.*\)/mv & MID-0\2\1\3/
'
1 Like
RudiC
December 8, 2017, 3:40pm
4
Slightly shorter:
ls *.txt | sed -r 's/^(.*_)S([0-9]{1,2}_)(.*)/mv & MID-0\2\1\3/; s/-0([0-9]{2})/-\1/'
1 Like
Xterra
December 8, 2017, 3:47pm
5
Rudy
Thanks a TON! Would you mind helping me understand what your code does?
I guess I do not understand all that well what the script is doing
Thanks once again!
************************************
Never mind! I got it