【问题标题】:How to have a global variable that has been read from a list that has filenames in bash?如何从具有 bash 文件名的列表中读取全局变量?
【发布时间】:2019-04-03 14:58:45
【问题描述】:

我有一个包含一堆类名的 txt 文件。

我想在 bash 脚本中逐行读取这些类名,并将该值分配给一个变量,以便在脚本的另一个命令中全局使用它。

FILES="files.txt"

for f in $FILES
do
  echo "Processing $f file..."
  # take action on each file. $f store current file name
  cat $f
done

【问题讨论】:

    标签: bash shell scripting scripting-language


    【解决方案1】:

    我假设files.txt 是一个类文件列表,每行一个类?

    while read class
    do : whatver you need with $class
    done < files.txt
    

    如果您有多个类文件,请使用数组。
    不要全部大写。

    file_list=( files.txt other.txt ) # put several as needed
    for f in "${file_list[@]}" # use proper quoting
    do : processing $f # set -x for these to log to stderr
       while read class
       do : whatver you need with $class
       done < "$f"
    done
    

    【讨论】:

    • 嘿,谢谢你的回答,所以当我添加需要 $class 属性变量的附加命令时,我应该在 de“do”部分使用它,对吗?完成后无法使用?
    • $class 变量的值不会在循环之后持续存在,但您可以在循环内设置foo=$class,之后$foo 仍将保留。
    【解决方案2】:

    假设文件中的每一行只包含一个类名,应该这样做:

    for f in $FILES
    do
      echo "Processing $f file..."
      while read class
      do 
        <something with "$class" >
      done < $f
    done
    

    【讨论】:

    • 我有一个包含多个文件路径的文件。我认为这对我不起作用。
    【解决方案3】:

    示例 1

    FILES="files.txt" 
    cat $FILES | while read class
    do
       echo $class  # Do something with $class
    done
    

    示例 2,由 Paul Hodges 评论

    FILES="files.txt"
    while read class
    do
       echo $class  # Do something with $class
    done < $FILES
    

    【讨论】:

    • 我有一个包含多个文件路径的文件。我认为这对我不起作用@PaulHodges
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2021-04-24
    • 1970-01-01
    相关资源
    最近更新 更多