user3313178 user3313178 - 1 year ago 52
Bash Question

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

#!/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_out.txt


  1. This doesn't quite work because I find is that the first
    replacement is completed fine but the second one is not. Is there a way for me to modify the script so that both
    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
    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?

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download