【问题标题】:Remove double quoted string from text file?从文本文件中删除双引号字符串?
【发布时间】:2017-11-10 23:47:03
【问题描述】:

我正在处理一些文本文件,我必须删除一个特定的字符串

ex: "1234_NAME=TRUE", (including double quotes and comma) 

如果我通过了使用 Vim 编辑器

:%s/"1234_NAME=TRUE",//g

但是这样我将手动进行。但我想通过使用一些脚本来自动化这项工作。

我尝试使用 sed 工具,但失败了。

sed 's/"1234_NAME=TRUE",//g' hello.txt

我不是脚本专家。我知道命令不正确。上述命令的解决方案是什么。

还有一个问题:

我们可以添加一个小循环,而不是手动传递文件名,它会一个一个地获取目录中的所有文本文件并删除字符串。

@codeforester 建议的答案需要一些修复:

for file in *.txt
do
   [[ -f "$file" ]] || continue 

分号是问题。

感谢@SlePort 的回答。

问候,

GBiradar

【问题讨论】:

  • sed 命令是正确的,只需使用sed -i.bak
  • 是的,我添加了 -i 它有效。但是我必须一次处理一个文件,我尝试使用 @codeforester 提到的 for 循环,但它没有用。
  • 知道了。我必须修复@codeforester 的答案。它奏效了。
  • 我的回答有什么问题?请相应更新。
  • for ...; do 是写for ... 然后do 在下一行的另一种方式。这不是问题。

标签: bash shell vim sed sh


【解决方案1】:

这可能对你有用:

sed -i.bak 's/"1234_NAME=TRUE",//g' *.txt
  • -i 就地编辑
  • .bak: 备份文件的扩展名

【讨论】:

  • 虽然 -i 不是标准的,但它也不是特定于 GNU sed
【解决方案2】:

你的命令是正确的。要遍历您的文件,您可以使用一个简单的循环:

for file in *.txt; do          # assuming your files are have .txt extension, modify accordingly
  [[ -f "$file" ]] || continue # skip if not a regular file
  sed 's/"1234_NAME=TRUE",//g' "$file" > "$file.modified" && mv "$file.modified" "$file"
  # you can also use the `-i` flag to make a backup of the file and then overwrite the original
  # `-i ''` will skip the backup and just overwrite the file
  # sed -i .bak 's/"1234_NAME=TRUE",//g' "$file"
done

确保在运行上述代码之前备份文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2012-09-26
    相关资源
    最近更新 更多