如何在linux shell中循环相同格式的文件

时间:2014-06-02 13:54:08

标签: linux shell loops sed

我想在各种*.dat文件中应用特定操作。我想要做的是使用sed使用

删除特定字符
sed 's/"//g' file.dat >file.dat

我尝试以下列方式使用上述代码

sed 's/"//g' *.dat > *.dat

但它似乎不适用于目录中的所有文件。

关于如何在linux shell中循环遍历所有文件的任何想法?

3 个答案:

答案 0 :(得分:2)

我会使用find命令和sed -i-i就地)。所以,完整的命令就像 -

find . -name "*.dat" -exec sed -i 's/\"//g' {} \;

答案 1 :(得分:1)

You can't read from a file and write to the same file in the same pipeline,所以

sed … file > file

会失败。实际上,它会截断文件。 sed的许多实现都包含非标准-i标志,该标志将写入的工作抽象为临时文件:

sed -i … file

所以你可以这样做:

for dat in *.dat; do
    sed -i 's/"//g' "$dat"
done

如果您的sed没有-i,则可以使用tr非常有效地从文件中删除单个字符:

for dat in *.dat; do
    tr -d '"' "$dat" > "$dat.tmp"
    mv "$dat.tmp" "$dat"
done

如果要以递归方式执行此操作(即,将文件嵌套在初始目标目录中的目录中),请使用bash的 globstar 设置或find

shopt -s globstar
for dat in **/*.dat; do … # the rest is the same as above

find . -name '*.dat' -exec sed -i 's/"//g' {} \;

答案 2 :(得分:1)

试试这段代码:

find . -type f -name *.dat -exec sed 's/"//g' {} > {} ';'