【问题标题】:bash for loop sed mind troublebash for loop sed 头脑麻烦
【发布时间】:2020-05-22 06:10:44
【问题描述】:

我想对多个 ifcg 文件执行 sed,但 'eth$i' 不会增加,每个文件中都有 eth0。 我的目标是在 eno1 eth0 里面,在 enps0 eth1 里面......

如果有人能帮忙,非常感谢

ls test
eno1  enps0  enps1  enps2  enps3  lo
cat test/eno1
name=eno1
device=eno1
for NAME in $(ls test/ | grep -v lo | sort)
do
        for (( i=0; i<$(ls test/ | grep -v lo | wc -l); i++ ))
        do
            sed -i "s/${NAME}/eth${i}/g" test/$NAME
        done
done

在决赛中我想拥有

cat test/eno1
name=eth0
device=eth0
cat test/enps0  
name=eth1
device=eth1
cat test/enps1   
name=eth2
device=eth2

...

谢谢

【问题讨论】:

  • 你想要的输出是什么?
  • 在外循环的第一次迭代中,NAME 设置为eno1。然后在内部循环中对文件eno1 执行 5 次迭代,i 绑定到 0..4。在第一次内部迭代中,您将文件eno1 中的字符串eno1 替换为eth0。在下一次迭代中(i 等于 1),您尝试将每个 eno1 替换为 eth1,但此文件中不再存在 eno1。因此它坚持eth0。您可以通过在sed 命令之后执行cat test/$NAME 轻松验证这一点。

标签: bash loops sed nic


【解决方案1】:

请您尝试以下方法:

i=0                                             # initialize the variable i
for f in test/*; do                             # loop over the files in the directory test/
                                                # note that you don't need to "sort" here
    name=${f##*/}                               # extract the basename of the file
    if [[ -f $f && $name != "lo" ]]; then       # if "$f" is a regular file and not "lo"
         sed -i "s/$name/eth${i}/" "$f"         # substitute the device name
         (( i++ ))                              # increment the value of i
    fi
done

【讨论】:

    【解决方案2】:

    当您将文件存储在数组中时,您可以将数组索引用于接口。

    cd test
    files=( e* )
    for ((i=0; i<${#files[@]}; i++)); do
        printf "name=eth%s\ndevice=eth%s\n" $i $i > "${files[i]}"
    done
    
    猜你喜欢
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 2013-03-14
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    相关资源
    最近更新 更多