简体   繁体   中英

Can't assign proper filenames in bash loop using variable extension

I'm stucked on this problem. I'm using a loop to iterate commands on every file into a specific directory. While using the original names of files to generate new files, using variables extensions, it only works if variable has no text before. I've got this code:

for f in temp/temp_orfs/* ; do
    wc -l $f > ${f}_temp
    gawk '{print $1}' ${f}_temp > temp/temp_orfs/num_${f}_text
done

${f}_temp ---> exists
num_${f}_text --> doesn't exists 

What I'm doing wrong?

f contains the temp/temp_orfs prefix, not just the name of the file in the directory. Let's say that f expands to temp/temp_orfs/foo ; then

  • ${f}_temp expands to temp/temp_orfs/foo_temp
  • temp/temp_orfs/num_${f}_text expands to temp/temp_orfs/num_temp/temp_orfs/foo_text

You want the base name instead:

for f in temp/temp_orfs/*; do
    bf=${f##*/}
    wc -l "$bf" | gawk '{print $1}' > "temp/temp_orfs/num_${bf}_text"
done

Or, you can simply change directory first:

cd temp/temp_orfs
for f in *; do
    wc -l "$f" | gawk '{print $1}' > "temp/temp_orfs/num_${f}_text"

(Either way, the temporary file isn't necessary, but if you really want it, be sure to pay attention to what its name will be so you know where it gets created.)


awk probably isn't necessary. You can use input redirection to make wc output just a line count, although there may be a slight difference in how the result is formatted, depending on which implementation of wc you use:

# GNU wc
$ wc -l < some_some_file
21

# BSD wc
$ wc -l < some_small_file
      21

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM