【问题标题】:calling and changing a file using sed command within a function在函数中使用 sed 命令调用和更改文件
【发布时间】:2023-03-24 15:29:02
【问题描述】:

您好,我在一个 shell 函数中封装了一个 sed 命令(它是自己的)。

#!/bin/bash

snp2fasta() { 
sed -i "s/^\(.\{'$2'\}\)./\1'$3'/" $1; 
}

并调用它

$ ./snp2fasta input.txt 45 A

没有对 input.txt 进行任何更改

但是如果我只是这样做

$ sed -i 's/^\(.\{45\}\)./\1A/' input.txt

然后这行得通,通过将第 45 个字符更改为 A 来更改文件。

然而,当包装成一个 shell 脚本(处理命令行变量)时,shell 脚本 snp2fasta.sh 运行良好,但对文件没有任何更改。

这是为什么?

【问题讨论】:

  • 这将是一个逃避问题。将 set -x 放在 sed 调用之前以查看它实际运行的内容。
  • 在 sed 命令之前使用 set -x 时,终端没有输出
  • 抱歉@Jayesh - 犯了一个错误 - 我确实将文件作为参数一并编辑了帖子
  • 嗨@Jayesh 我在第二个代码块中调用 ./snp2fasta - 我从命令行调用它。你是这个意思吗?
  • @brucezepplin 好的..看看。 shell 不会扩展单引号内的变量。尝试在"".like sed -i 's/^\(.\{"$2"\}\)./\1"$3"/' "$1";中使用扩展变量

标签: bash shell sed


【解决方案1】:

如果你把它放到一个脚本中,就不需要在脚本之外调用函数了,直接在脚本中使用吧。

就像在其他相关帖子 (Use argument to...) 上一样,声明它(以确保 $1,2 和 3 的内容)

#!/bin/bash

# argument passed to script (or any other source if needed like intern to script)
File=$1
Place=$2
NewChar=$3

# sed with unambigous variable content
sed -i "s/^\(.\{${Place}\}\)./\1${NewChar}/" ${File}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 2022-10-24
    • 2023-03-28
    • 2018-10-07
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多