繁体   English   中英

如何在shell脚本中替换变量

[英]how to substitute the variable in shell script

在下面的脚本中,我想将文件名作为前缀添加到grep生成的每个输出行。 我不知道为什么这不是用$ file代替文件名,我以$ file作为前缀。有人可以帮我吗

function traverse() {
  for file in "$1"/*
  do
    if [ ! -d "${file}" ] ; then
      if [ ${file: -2} == ".c" ]
      then
        ./sed.sed "$file"  >  latest_log.txt #To remove all the comments
        grep -nir "$2"   latest_log.txt >> output.log #grep matched lines
        sed -i "s/^/$file/" output.log > grepoutput3.txt #prefix filename($file here)
        echo "${file} is a c file"
      fi
    else
      traverse "${file}" "$2"
    fi
  done
}

function main() {
  traverse "$1" "$2"
}

main "$1" "$2"

下面的行应将文件名添加为前缀,但是$ file不能替换,除了整个脚本工作正常之外。

sed -i "s/^/$file/" ex.txt > grepoutput3.txt

例如:在一个文件夹的所有.c文件中搜索“欢迎”。以first_file.c为一个。

FIRST_FILE.C

欢迎到这里

/* 欢迎到这里 */

//欢迎到这里

欢迎来到这里2

预期产量

/DIR/FIRST_FILE.C:1:欢迎在这里

/DIR/FIRST_FILE.C:4:欢迎来到这里2

用我的脚本,输出是

1:欢迎来到这里

4:欢迎来到这里2

因此,我正在尝试在每行前面添加文件名(/DIR/FIRST_FILE.C)。我们可以从$ file中获取该文件名,但是sed不能解释它。

脚本中无处创建ex.txt代码。 那是故意的吗? 要调试此脚本,请在开头附近的set -x下运行脚本。

同样值得注意的是:您已将此问题标记为“ sh”(不是bash),但

if [ ${file: -2} == ".c" ]

充满了不可移植的bashisms:字符串相等运算符为= ,POSIX sh无法理解${file: -2}语法。 等效的sh代码将使用

case $file in
(*.c) ...;;
esac

对于文件系统遍历: 使用find

find FOLDER -type f -name '*.c' -exec bash yourscript.sh {} \;

yourscript.sh中,您可以访问$1的文件名。

我可以进一步帮助实现该脚本,但目前尚不清楚您要做什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM