通过批处理脚本实现自动化和循环



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

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: '$' 

具有文件路径列表的某个文件的示例

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 ............

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

一个目录中有三个文件:

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 ............

这就是你想要实现的吗?如果你需要进一步的澄清,我很乐意编辑这个答案,以提供更多的细节/解释。

ls -l somefile | grep .txt | awk 'print $4}' | while read file 

没有。不,不,不。

ls -l somefile只会显示somefile,除非它是一个目录
(不要将目录命名为"somefile"。(
如果你指的是somefile.txt,请在你的帖子中澄清。

grep .txt将浏览前面有任何字符的三个字符txt的行(点是regex通配符(。由于您要求somefile的长列表,所以不应该找到任何内容,因此不应该传递任何内容。

awk 'print $4}'是一个打字错误,无法编译。awk将崩溃。

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

for file in *.txt

然后在中

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

它忘记了你对$file的期望——awk的4美元来自ls -l似乎不太可能
假设是上面for中的文件名,则尝试

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

这有帮助吗?根据需要纠正我。对不起,如果我看起来很严厉
欢迎使用SO;(

最新更新