linux - 传递文件名并运行的shell脚本

标签 linux bash shell sed

<分区>

我有文件名列表 file1、file2、file3
我想在脚本中传递这些文件名并删除特殊字符

我准备了sed命令来删除特殊字符

sed  -i -e 's/^B/,/g' /home/data/nfiledata/ 
hdfs dfs -put -f /home/data/nfiledata/*  user/sai/table1/nfiledata/
gzip  /home/data/nfiledata/*

sed  -i -e 's/^B/,/g' /home/data/marginfile/  
hdfs dfs -put -f /home/data/marginfile/*  user/sai/table2/marginfile/
gzip  /home/data/marginfile/*

sed  -i -e 's/^B/,/g' /home/data/calldata/  
hdfs dfs -put -f /home/data/calldata/*  user/sai/table3/calldata/
gzip  /home/data/calldata/*

我的问题是,我可以写一个命令并使用 Shell 脚本为每个文件循环处理,而不是多次编写相同的命令

nfile = (nfiledata,margindata, calldata)
while IFS= read -r nfile
do
  sed  -i -e 's//,/g' /home/data/$nfile/
  hdfs dfs -put -f /home/data/$nfile/*  user/sai/table$/$nfile/
  gzip  /home/data/$nfile/*
done < "home/data/$nfile"

最佳答案

for 循环,而不是 while read 循环,在这里是合适的:

nfile=(file1 file2 file3)
for f in "${nfile[@]}"; do
  sed  -i -e 's/^B/,/g' /home/data/"$f"/ # should this be "$f"/* ?
  hdfs dfs -put -f /home/data/"$f"/*  user/sai/table1/"$f"/
  gzip /home/data/"$f"/*
done

值得注意的组件:

  • 分配的 = 两边不能有空格。逗号不是 bash 中数组语法的一部分——未加引号、未转义的空格在这种情况下和其他地方一样充当分隔符。
  • $f 等扩展必须在双引号内才能安全执行(无需字符串拆分或通配)。
  • 全局扩展,如 *,必须在引号外才能生效。

关于linux - 传递文件名并运行的shell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37469931/

相关文章:

bash - 如何找到当前目录下的可执行文件并找出它们的扩展名?

javascript - Meteor 应用程序 - 如何为多实例部署实现编排/配置?

linux - 电子邮件中的 df nice 输出格式

linux - 为什么参数-type d在find命令中不生效?

c++ - 我如何使用 C++ 在 Linux 中制作托盘图标?

linux - 如何使用 makefile 创建测试结果

linux - 无需交互的 Bash 脚本

php 脚本在 Linux 启动时不执行

linux - SMTP(500 Access Denied) 错误,但我可以将邮件发送到 gmail 或 hotmail

linux - 引用参数字符串 Shell