简体   繁体   English

无法使用变量扩展名在bash循环中分配正确的文件名

[英]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. f包含temp/temp_orfs前缀,而不仅仅是目录中文件的名称。 Let's say that f expands to temp/temp_orfs/foo ; 假设f扩展为temp/temp_orfs/foo ; then 然后

  • ${f}_temp expands to temp/temp_orfs/foo_temp ${f}_temp扩展为temp/temp_orfs/foo_temp
  • temp/temp_orfs/num_${f}_text expands to temp/temp_orfs/num_temp/temp_orfs/foo_text temp/temp_orfs/num_${f}_text扩展为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. awk可能不是必需的。 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: 您可以使用输入重定向来使wc输出仅占行数,尽管结果的格式可能略有不同,具体取决于您使用的wc实现方式:

# GNU wc
$ wc -l < some_some_file
21

# BSD wc
$ wc -l < some_small_file
      21

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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