【问题标题】:Editing line with sed in for loop from other file使用 sed in for 循环从其他文件编辑行
【发布时间】:2021-05-04 06:28:45
【问题描述】:

我是 bash 的新手,

我正在尝试使用 sed 和其他文件中的 for 循环来编辑行。

请告诉我我在小代码中做错了什么?

我错过了另一个循环吗?

#!/bin/bash

# read and taking the line needed:
for j in `cat /tmp/check.txt`; do 

# replacing the old value with and value:
sed -i "s+/tmp/old_name/+/${j}/+gi" file_destantion.txt$$ 

#giving numbers to the logs for checking
Num=j +1

# moving the changed file to .log number ( as for see that it is changed):
mv file_destantion.txt$$ file_destantion.txt$$.log$Num

#create ne source file to do the next value from /tmp/check:
cp -rp file_destantion.txt file_destantion.txt$$ 

done

在 /tmp/check 我有我想在每个循环转弯时输入的信息。

在/tmp/检查:

/tmp/check70
/tmp/check70_1
/tmp/_check7007
  • 最后这就是我想要的样子:
.log1 > will contain /tmp/check70
.log2 > will contain /tmp/check70_1
.log3 will contain /tmp/check7007

【问题讨论】:

  • 请添加一个shebang,然后将您的脚本粘贴到shellcheck.net 并尝试实施那里提出的建议。
  • 除了 shellcheck.net 将显示的语法错误之外,您还在做什么?第一次调用sed 时,所有带有/tmp/old_name/ 的行都将替换为check.txt 中的第一个单词。使用sed 的所有其他尝试都将失败,因为找不到带有/tmp/old_name/ 的行。

标签: bash shell unix syntax


【解决方案1】:

我发现这个解决方案对我有用。

#!/bin/bash
count=0
grep -v '^ *#' < /tmp/check | while IFS= read -r line ;do
cp -rp file_destantion.txt file_destantion.txt$$
sed -i "s+/tmp/old_name/+${line}/+gi" file_destantion.txt$$
(( count++ ))
mv file_destantion.txt$$ "file_destantion.txt$$.log${count}"
cp -rp file_destantion.txt file_destantion.txt$$
done

非常感谢@Cyrus 的指导。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多