【问题标题】:Automate and looping through batch script自动化和循环批处理脚本
【发布时间】:2020-12-14 16:56:48
【问题描述】:

我是批处理新手。我想遍历一个列表并使用输出内容替换另一个文件中的字符串。

ls -l somefile | grep .txt | awk 'print $4}' | while read file
do
  toreplace="/Team/$file"
  sed 's/dataFile/"$toreplace"/$file/ file2 > /tmp/test.txt
done

当我运行代码时出现错误

 sed: 1: "s/dataFile/"$torepla ...": bad flag in substitute command: '$' 

包含文件路径列表的 somefile 示例

foo/name/xxx/2020-01-01.txt
foo/name/xxx/2020-01-02.txt
foo/name/xxx/2020-01-03.txt

但是,我想要的输出是使用 somefile 目录中的文件路径列表来替换另一个 file2 内容中的字符串。像这样的:

This is the directory of locations where data from /Team/foo/name/xxx/2020-01-01.txt ............

【问题讨论】:

    标签: linux bash automation batch-processing


    【解决方案1】:

    我不确定我是否理解您想要的结果,但希望这能帮助您解决问题:

    您在一个目录中有三个文件:

    TEAM/foo/name/xxx/2020-01-02.txt
    TEAM/foo/name/xxx/2020-01-03.txt
    TEAM/foo/name/xxx/2020-01-01.txt
    

    您还有另一个名为 to_be_changed.txt 的文件,其中包含文本 This is the directory of locations where data from TO_BE_REPLACED ............,并且您想获取三个文件的文件名并将它们插入到您的 to_be_changed.txt 文件中,您可以这样做:

    while read file
    do
      filename="$file"
      sed "s/TO_BE_REPLACED/${filename##*/}/g" to_be_changed.txt >> changed.txt
    done < <(find ./TEAM/ -name "*.txt")
    

    然后您将创建一个名为 changed.txt 的文件,其中包含:

    This is the directory of locations where data from 2020-01-02.txt ............
    This is the directory of locations where data from 2020-01-03.txt ............
    This is the directory of locations where data from 2020-01-01.txt ............
    

    这是您想要实现的目标吗?如果您需要进一步说明,我很乐意编辑此答案以提供更多详细信息/解释。

    【讨论】:

      【解决方案2】:
      ls -l somefile | grep .txt | awk 'print $4}' | while read file 
      

      没有。不不不。

      ls -l somefile 只会显示somefile,除非它是一个目录。
      (不要将目录命名为“somefile”。)
      如果您的意思是somefile.txt,请在您的帖子中说明。

      grep .txt 将查看前面有任何字符(点是正则表达式通配符)的三个字符 txt 的行。由于您要求提供很长的 somefile 列表,因此它应该找不到任何内容,因此不应传递任何内容。

      awk 'print $4}' 是一个无法编译的错字。 awk 会崩溃。

      保持简单。我怀疑你的意思是

      for file in *.txt
      

      然后在

      toreplace="/Team/$file"
      sed 's/dataFile/"$toreplace"/$file/ file2 > /tmp/test.txt
      

      您对$file 的期望是未知的-awk 从ls -l 获得的 4 美元似乎不太可能。
      假设是上面for 的文件名,那么试试

       sed "s,dataFile,/Team/$file," file2 > /tmp/test.txt
      

      这有帮助吗?根据需要纠正我。对不起,如果我看起来很苛刻。
      欢迎来到 SO。 ;)

      【讨论】:

        猜你喜欢
        • 2011-02-05
        • 1970-01-01
        • 1970-01-01
        • 2013-04-08
        • 2015-06-11
        • 1970-01-01
        • 2011-08-26
        • 2015-12-15
        • 1970-01-01
        相关资源
        最近更新 更多