0

I want to retrieve the first part of a file name and iterate through a list of files. File names are paired and I'm trying to run a program on each pair. This is what they look like:

H1T1A-left.fastq.gz
H1T1A-right.fastq.gz

I can strip everything after the - to get unique names:

for d in *left*; do
    echo $d | cut -d- -f1;
    echo "Mapping $NAME";
done

H1T1A
H1T1B
H1T1C
H1T2A
H1T2B

But if I want to load that in to variable "NAME" so I can pass it to a program:

for d in *left*; do
    NAME = echo $d | cut -d- -f1;
    echo "Mapping $NAME";
done

And I get an error:

NAME: command not found
Mapping
NAME: command not found
Mapping

I'd like to be able to pass $NAME as part of a filename for each pair:

>program "$NAME"-left.file "$NAME"-right.file
user974887
  • 2,309
  • 3
  • 17
  • 18
  • 2
    Syntax issue, try your code here (https://www.shellcheck.net/) first, make sure your syntax is ok. Then post here for logic problems. And http://mywiki.wooledge.org/BashGuide/Parameters – Nic3500 Jan 26 '18 at 19:10
  • I want to take $d | cut -d- -f1 and put the result in NAME so I can use the first part of the filename. Echo isn't the way to do it, so how would that work? – user974887 Jan 26 '18 at 19:13
  • This doesn't work *outside* a for loop either. Part of building a good [mcve] is testing taking things away / simplifying until the problem stops happening -- if you'd tried taking away the loop, the issue still would have occurred. – Charles Duffy Jan 26 '18 at 19:19
  • Didn't know about Shellcheck, that's super great – user974887 Jan 26 '18 at 19:21
  • BTW, you can (and should!) do this without `cut`; ie. `name=${d%%-*}` -- you'll see a very big difference in performance if you run this on a directory with tens or hundreds of files matching `*left*`. – Charles Duffy Jan 26 '18 at 19:27

1 Answers1

3

Remove the whitespaces around the assignment = if you want to store the output of a commnad in some variable, put the command inside $(yourcommand)

 #!/bin/bash
    for d in *left*; do
        NAME=$(echo $d | cut -d- -f1)
        echo "Mapping $NAME";
    done
Ashutosh Bharti
  • 367
  • 2
  • 10
  • 1
    `echo "$d"`, not `echo $d`. If `d='left * right'` (which is a perfectly valid filename!), then `echo $d` will have the names of all the files in your current directory, preceded by `left` and succeeded by `right`. – Charles Duffy Jan 26 '18 at 19:21
  • 1
    Also, note [How to Answer](https://stackoverflow.com/help/how-to-answer), particularly the section "Answer well-asked questions", particularly the bullet regarding questions which "*have already been asked and answered many times before*". – Charles Duffy Jan 26 '18 at 19:24
  • 1
    Also, it'd be even more efficient to run `NAME=${d%%-*}`, which avoids the performance cost of running a subshell and spinning up the (external, not-part-of-bash) `cut` command. – Charles Duffy Jan 26 '18 at 19:25