如何在 sed 命令中使用文件名?

foo*_*ise 8 command-line bash sed text-processing

我有许多.conf相同且位于同一目录中的文件,但文件名不同。在每个唯一命名的.conf文件中,我想用文件名替换文件中的一组字符。例如:

当前在所有文件中:

datafname = example.nex
ofprefix = best.example
Run Code Online (Sandbox Code Playgroud)

理想输出:

文档名称: 25.conf

datafname = 25.nex
ofprefix = best.25
Run Code Online (Sandbox Code Playgroud)

文档名称: 26.conf

datafname = 26.nex
ofprefix = best.26
Run Code Online (Sandbox Code Playgroud)

我想我可以sed用来遍历所有这些文件,以使用以下内容查找文本字符串并将其替换为文件名:

sed -i conf 's/example/echo $f/g' *
Run Code Online (Sandbox Code Playgroud)

但这不能正常工作。有人会碰巧对如何做到这一点提出建议吗?

Per*_*uck 11

你可以做:

for f in *.conf; do
    base=$(basename "$f" '.conf') # gives '25' from '25.conf'
    sed -i.before "s/example/$base/g" "$f"
done
Run Code Online (Sandbox Code Playgroud)

使用-i切换到 时sed,您必须绝对确定您的sed命令有效,因为就地-i更改了文件。这意味着生成的输出将覆盖输入文件。如果您的替换命令 ( ) 是错误的,您最终可能会得到空文件并且没有备份。因此,我使用which 将留下一个包含原始内容的文件。 s/…/…/-i.before*.before


cho*_*oba 5

您可以使用 for 循环遍历文件。使用参数扩展删除文件扩展名。在表达式周围使用双引号,否则变量不会被扩展。

#! /bin/bash
for f in *.conf ; do
    b=${f%.conf}
    sed -i "s/example/$b/" "$f"
done
Run Code Online (Sandbox Code Playgroud)