0

I am looking to replace an entire line in one .sh file with another .sh file using the sed -i command in bash.

The command pattern sed <line number>s/<search pattern>/<replacement string>/ and I'm replacing the entire line with a replacement string that contains a $ variable.

The first file write.sh contains the information that must be written to the second file insert.sh.

#!/bin/bash

output_file="/random/path/that/should/be/there1/"
error_file="/random/path/that/should/be/there2/"

sed -i '2s/.*/#SBATCH --job-name=775_none/' insert.sh
sed -i '3s/.*/#SBATCH --cpus-per-task=1/' insert.sh
sed -i '4s/.*/#SBATCH --mem=5GB/' insert.sh
sed -i '5s/.*/#SBATCH --output="'$output_file'"/' insert.sh
sed -i '6s/.*/#SBATCH --error="'$error_file'"/' insert.sh
sed -i '7s/.*/#SBATCH --time=5:00:00/' insert.sh

All lines work except for lines 5s and 6s with the error returning:

sed: -e expression #1, char 27: unknown option to `s'
sed: -e expression #1, char 26: unknown option to `s'

The second file insert.sh contains:

#!/bin/bash
#SBATCH --job-name=none-chi-1
#SBATCH --cpus-per-task=1
#SBATCH --mem=5GB
#SBATCH --output=/path/i/want/to/repalce
#SBATCH --error=/path/i/want/to/repalce
#SBATCH --time=8:00:00

and what I would like is

#!/bin/bash
#SBATCH --job-name=775_none
#SBATCH --cpus-per-task=1
#SBATCH --mem=5GB
#SBATCH --output=/random/path/that/should/be/there1/
#SBATCH --error=/random/path/that/should/be/there2/
#SBATCH --time=5:00:00

Some links I have checked: 1, 2, 3

Any assistance would be appreciated if this is possible.

B.Eng
  • 23
  • 4
  • Can you show original content of `insert.sh` and your expected output – anubhava Nov 08 '22 at 07:27
  • 1
    The immediate problem is that you can't use slashes as delimiters when your data contains unescaped slashes. More fundamentally, repeatedly running `sed -i` on the same file is inelegant, inefficient, and error-prone. Try `sed -i -e '2s/.*/#SBATCH --job-name=775_none/' -e '3s/.*/#SBATCH --cpus-per-task=1/' -e '4s/.*/#SBATCH --mem=5GB/'` etc – tripleee Nov 08 '22 at 07:27
  • 1
    Also, you want the strings to remain quoted, like `-e '5s%.*%#SBATCH --output="'"$output_file"'"%'` or just `"5s%.*%#SBATCH --output=\"$output_file\"%"` – tripleee Nov 08 '22 at 07:29
  • 1
    Perhaps also review the [Stack Overflow `sed` tag info page](/tags/sed/info) which has links to common FAQs, including most of what was discussed here. – tripleee Nov 08 '22 at 07:31

0 Answers0