在sed中使用外部变量


=Start=

缘由:

在编写一个Bash脚本时需要用sed命令对结果进行精简(将某个字符串中经常出现的公共子串用一个短变量名表示),最初的写法是:

find "${base_path}" -maxdepth 1 -type f -iname "*.py*" 2>/dev/null | xargs | tr ' ' ';' | sed -e 's#${base_path}#\${base_path}#g'

但是没有起到作用,当时也比较忙,没有仔细检查问题出在哪了,只是先简单的把最后的sed替换命令给去掉了。现在刚好有点时间,找到了解决办法,在此记录一下,方便以后参考。

正文:
搜索关键字:

linux bash sed search with var

参考解答:

三种方法:

  1. 使用「双引号」而不是「单引号」
  2. 使用多重「单引号」
  3. 使用Bash内置的字符串替换操作(效率最高)。

测试用例如下:

#!/bin/bash

base_path="/root/port_scan"
echo $base_path

py_files="/root/port_scan/py_get_new_port_list2.py.2016-05-19 /root/port_scan/py_get_new_port_list2.py.2016-05-17"
echo $py_files
# echo $py_files | sed -e 's#${base_path}#\${base_path}#g'
echo $py_files | sed -e "s#${base_path}#\${base_path}#g"    #work
echo $py_files | sed -e 's#'${base_path}'#\${base_path}#g'  #work
echo $py_files | sed -e 's#"${base_path}"#\${base_path}#g'
echo $py_files | sed -e 's#/root/port_scan#\${base_path}#g'
echo ${py_files//$base_path/\$base_path}                    #ok
echo ${py_files//$base_path/\${base_path\}}                 #work
参考链接:
另:

之前在使用awk的时候也遇到过一个类似的问题:在awk中使用外部变量。在此也顺便记录一下:如果需要在awk中使用外部的变量,可以借助awk的「-v」选项。

参考链接:

=END=

, , ,

《 “在sed中使用外部变量” 》 有 4 条评论

  1. 1.在一个sed命令中进行多次替换操作;
    方法一:用大括号包起来
    `echo “url = [email protected]:taizilongxu/interview_python.git” | sed ‘{s#:#/#; s#git@#https://#;}’
    `
    方法二:用多个「-e」选项
    `echo “url = [email protected]:taizilongxu/interview_python.git” | sed -e ‘s#:#/#’ -e ‘s#git@#https://#’
    `
    2.在匹配到的行上进行替换操作;
    `sed -i ‘/url = git@github/{s#:#/#; s#git@#https://#;}’ .git/config
    `

    http://unix.stackexchange.com/questions/155331/sed-replace-a-character-in-a-matched-line-in-place
    http://stackoverflow.com/questions/7573368/in-place-edits-with-sed-on-os-x

  2. awk中如何使用外部变量的方法
    Can we use shell variables in awk?
    https://stackoverflow.com/questions/15786777/can-we-use-shell-variables-in-awk
    `
    # 方法一:使用 -v 选项先定义一个变量
    Yes, you can use the shell variables inside awk. There are a bunch of ways of doing it, but my favorite is to define a variable with the -v flag:

    $ echo | awk -v my_var=4 ‘{print “My var is ” my_var}’
    My var is 4

    # 方法二:使用awk内置的 ENVIRON 数组来读取已export过的变量
    Awk and Gawk provide the ENVIRON associative array that holds all exported environment variables. So in your awk script you can use ENVIRON[“VarName”] to get the value of VarName, provided that VarName has been exported before running awk.

    Note ENVIRON is a predefined awk variable NOT a shell environment variable.
    `

  3. Learning AWK Programming by Shiwang Kalkhanda
    https://www.oreilly.com/library/view/learning-awk-programming/9781788391030/15d45842-3a9a-4d0d-b96e-0b6b8d544f98.xhtml
    `
    awk ‘BEGIN { OFS=”=”; for( v in ENVIRON ) print v, ENVIRON[v]; }’

    The environment variable is an associative array containing the values of environment variables for the current process. The index of the array stores the environment variable name, and the elements are the values of particular environment variables. It is also helpful when we want to access the shell environment variable in our AWK script.

    For example, the array element ENVIRON[“HOME”] will contain the value of the HOME environment variable, ENVIRON[“PATH”] will contain the value of the PATH environment variable, and so on.
    `

    awk – Passing arguments or shell variables to awk
    https://www.theunixschool.com/2011/09/awk-passing-arguments-or-shell.html
    `
    $ x=3
    $ echo $x
    3
    $ export x
    $ echo | awk ‘{print $0,ENVIRON[“x”]}’ OFS=,
    `

  4. How to replace an entire line in a text file by line number
    https://stackoverflow.com/questions/11145270/how-to-replace-an-entire-line-in-a-text-file-by-line-number
    `
    # 将文件 file.txt 中的第1行内容直接替换为【replacement_line】
    # 如果想替换其它行,直接将1修改成指定的行号即可
    sed -i ‘1s/.*/replacement_line/’ file.txt

    # 将文件 file.txt 中的第1行内容替换为【replacement_line】之后将新内容存成文件 new_file.txt
    sed ‘1s/.*/replacement_line/’ file.txt > new_file.txt
    `

    Most efficient way of changing 1 line in a file
    https://unix.stackexchange.com/questions/604376/most-efficient-way-of-changing-1-line-in-a-file
    `
    find . -type f -exec sed -i ‘1s|^#!/bin/bash|#!/bin/sh|’ {} +
    `

    Replace the first line in a text file by a string
    https://stackoverflow.com/questions/13438095/replace-the-first-line-in-a-text-file-by-a-string

    How to replace the first line using sed?
    https://unix.stackexchange.com/questions/162838/how-to-replace-the-first-line-using-sed

    Replace text of a specific line number using sed
    https://askubuntu.com/questions/849930/replace-text-of-a-specific-line-number-using-sed
    `
    $ sed ‘1 s/AccountSettings/Users/’ input.txt
    $ perl -pi -e ‘s/AccountSettings/Users/ if $. == 1’ input.txt #就地置换了
    $ awk ‘NR==1{sub(“AccountSettings”,”Users”)};1’ input.txt

    $ python -c ‘import sys;print(“\n”.join([ l.strip().replace(“AccountSettings”,”Users”) if i==0 else l.strip() for i,l in enumerate(sys.stdin)]))’ < input.txt

    $ ruby -pe '$_=$_.sub(/AccountSettings/,"Users") if $. == 1' input.txt
    `

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注