0

I'm writing a script to substitute part of the words in my file. I want the line change to (first part of the file name).fastq.gz

I had

for file in ls /pathway *.sam | sort | uniq

do sed -i "s/VFC-00012-02.fastq.gz/${filename}.fastq.gz/g" $file

done

I got the part blank after the running this script

I want (with file named B (B.extensions))

B.fastq.gz in the text

after the sed command

I solved this issue with the help from https://askubuntu.com/questions/1011839/how-do-i-use-file-names-in-a-sed-command

7
  • 1
    Why the do at the beginning of the command? Is this part of a loop that you're not showing us? Since the sed expression is in single quotes, $filename will not be expanded in case you're expecting that. FInally, you don't have a space between the final quote and $file so that variable is being taken as part of the sed expression.
    – doneal24
    Sep 6, 2022 at 19:47
  • I had #!/usr/bin/bash and for file in before the do command.
    – cthieeewoi
    Sep 6, 2022 at 19:50
  • but if I use $file, it would include the file extension that I don't want
    – cthieeewoi
    Sep 6, 2022 at 19:52
  • So how is $filename set? If you want it expanded in the expression you'll need to use double quotes instead of single quotes.
    – doneal24
    Sep 6, 2022 at 19:54
  • I didn't set $filename, do i need to set this before this line?
    – cthieeewoi
    Sep 6, 2022 at 20:14

1 Answer 1

0

You need a space after the closing single quote. Otherwise, the shell interprets the filename as part of the substitution.

sed -i 's/VFC-00012-02.fastq.gz/$filename.fastq.gz/' "$file"

It's a good practice to double quote the variable so it doesn't undergo word splitting.

On the other hand, not double quoting the variable ($filename) means the it won't be expanded at all, i.e. the file will contain the literal dollar sign. I'm not sure it's what you want.

You can switch to double quotes to expand the $filename, but then you have to be careful if it can contain sed special characters, as the shell expands the variable before sed sees the argument, so sed doesn't know the characters came from a variable originally.

4
  • Note that $filename is not being expanded since it is inside single quotes.
    – doneal24
    Sep 6, 2022 at 19:55
  • Thank you so much ! now I got the sed works, but it turns out having $filename.fastq.gz on the file instead of having the file name
    – cthieeewoi
    Sep 6, 2022 at 20:01
  • I used sed -i 's/VFC-00012-02.fastq.gz/"$filename".fastq.gz/' $file and sed -i 's/VFC-00012-02.fastq.gz/$"filename.fastq.gz"/' $file , they gave "$filename" and $"filename"
    – cthieeewoi
    Sep 6, 2022 at 20:13
  • Nothing expands inside single quotes.
    – choroba
    Sep 6, 2022 at 20:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .