Problems with basename in a loop

6,886

Solution 1

You've put single quotes around '/home/rafaeldaddio/Documents/teste/*'. This means that it is looking for a single file called * inside teste. (I doubt you have such a file, or that that's what you intended!).

This means your for loop is running with a single entry, and passing that file * to basename.

Then, out=$(basename $arqin) is expanding to out=$(basename file1 file2 file3 ... fileN) which of course is too many arguments for basename.

Simple solution: take the quotes away from around /home/rafaeldaddio/Documents/teste/*.

Solution 2

@BenXO already told you why that failed but you don't really need a script for something this simple anyway. You could just paste this directly into the command line:

for arqin in /home/rafaeldaddio/Documents/teste/*; do 
    cat "$arqin" | 
      /home/rafaeldaddio/Documents/LX-Tagger/POSTagger/Tagger/run-Tagger.sh > \
        /home/rafaeldaddio/Documents/$(basename "$arqin"); 
done

Or, since if cat foo | program works, program foo almost certainly also works and assuming that /home/rafaeldaddio/ is your home directory, you can simplify to:

for arqin in ~/Documents/teste/*; do
 ~/Documents/LX-Tagger/POSTagger/Tagger/run-Tagger.sh "$arqin" > \
     ~/Documents/$(basename "$arqin");
done
Share:
6,886

Related videos on Youtube

Rafael
Author by

Rafael

Updated on September 18, 2022

Comments

  • Rafael
    Rafael over 1 year

    I am new at shell script programming and I'm trying to execute a software that reads a text and perform it's POS tagging. It requires an input and an output, as can be seen in the execute example:

    $ cat input.txt | /path/to/tagger/run-Tagger.sh > output.txt
    

    What I'm trying to do is to execute this line not only for a text, but a set of texts in an specific folder, and return the output files with the same name as the input files. So, I tried to do this script:

    #!/bin/bash
    path="/home/rafaeldaddio/Documents/"
    program="/home/rafaeldaddio/Documents/LX-Tagger/POSTagger/Tagger/run-Tagger.sh"
    
    for arqin in '/home/rafaeldaddio/Documents/teste/*'
    do
    out=$(basename $arqin)
    output=$path$out
    cat $arqin | $program > $output
    done
    

    I tried it with only one file and it works, but when I try with more than one, I get this error:

    basename: extra operand ‘/home/rafaeldaddio/Documents/teste/3’
    Try 'basename --help' for more information.
    
    ./scriptLXTagger.sh: 12: ./scriptLXTagger.sh: cannot create /home/rafaeldaddio/Documents/: Is a directory
    

    Any insights on what I'm doing wrong? Thanks.