user3313178
user3313178

Reputation: 119

Issue with two sed replacements in a bash script and looping over many input files and outputting them

I have two replacements in a file that I want to implement from a bash script.

So far I have a shell script called test.sh:

#!/usr/bin/env bash

# 1. change Hybridization REF to Hybridization_REF
# 2. change Composite Element REF to Composite_Element_REF

sed 's/Hybridization REF/Hybridization_REF/g' test_input.txt
sed 's/Composite Element REF/Composite_Element_REF/' test_input.txt

From the command line I then run $ test.sh > test_out.txt

Questions

  1. This doesn't quite work because I find is that the first sed replacement is completed fine but the second one is not. Is there a way for me to modify the script so that both sed replacements go as planned?

  2. Ideally I want to automate this for over 1000 files, which are all in the same folder and share the same prefix tumMeth and then output these 1000 input files to 1000 corresponding output files with the same name. Is there a way to incorporate a loop into the above script to achieve this?

Upvotes: 2

Views: 54

Answers (2)

jaypal singh
jaypal singh

Reputation: 77145

Canonical way of calling multiple sed statements in a file is to put them in a sed script.

#!/bin/sed -f

s/Hybridization REF/Hybridization_REF/g
s/Composite Element REF/Composite_Element_REF/

Store the above code in a file, say substitution.sed, make it executable by doing chmod u+x substitution.sed and execute like

substitution.sed < test_input.txt > test_out.txt

Upvotes: 0

anubhava
anubhava

Reputation: 785611

You can combine both sed commands into one and run a loop for your input file:

#!/usr/bin/env bash

for f in tumMeth*; do
    sed 's/Hybridization REF/Hybridization_REF/g; s/Composite Element REF/Composite_Element_REF/' "$f" > "$f.out"
done

Upvotes: 1

Related Questions