【问题标题】:How do I store file names that have spaces in a variable in shell script如何在shell脚本的变量中存储有空格的文件名
【发布时间】:2020-07-08 12:28:26
【问题描述】:

您好,我有一个名为 MYFILES.txt 的文本文件

当我运行 grep --null ".txt" MYFILES.txt 时,它会正确显示带有空格字符的文件名

grep --null ".txt" MYFILES.txt

my file 1.txt
my file 2.txt
my file 3.txt
my file 4.txt

但是在 shell 脚本中,如果我有这样的东西,那么空格字符将被排除: 我需要存储我从 FILE 变量中的文本中提取的每个文件名,并包含空格字符

for FILE in $( grep --null ".txt" MYFILES.txt)
do
   echo "${FILE}"
done

my
file
1.txt
my
file
2.txt
my
file
3.txt
my
file
4.txt

【问题讨论】:

标签: linux shell grep sh


【解决方案1】:

如果文件名不包含换行符

grep .txt MYFILES.txt | while IFS= read -r file ; do
    echo "$file"
done

【讨论】:

  • 在每行保留前导/尾随空格:while IFS= read -r file; ... -- 该调用将准确读取每一行。
猜你喜欢
  • 1970-01-01
  • 2015-11-13
  • 2013-12-25
  • 2014-09-26
  • 2011-08-02
  • 1970-01-01
相关资源
最近更新 更多