How to replace a value with the output of a command in a text file?

后端 未结 2 1637
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 16:12

I have a file that contains:

I want to replace in bash, the value 0

相关标签:
2条回答
  • 2020-12-09 16:38

    When the replacement string has newlines and spaces, you can use something else. We will try to insert the output of ls -l in the middle of some template file.

    awk 'NR==FNR {a[NR]=$0;next}
        {print}
        /Insert index here/ {for (i=1; i <= length(a); i++) { print a[i] }}'
        <(ls -l) template.file
    

    or

    sed '/^Insert after this$/r'<(ls -l) template.file
    
    0 讨论(0)
  • 2020-12-09 16:43

    In general, do use this syntax:

    sed "s/<expression>/$(command)/" file
    

    This will look for <expression> and replace it with the output of command.


    For your specific problem, you can use the following:

    sed "s/0/$(date +%s)/g" input.txt > output.txt
    

    This replaces any 0 present in the file with the output of the command date +%s. Note you need to use double quotes to make the command in $() be interpreted. Otherwise, you would get a literal $(date +%s).

    If you want the file to be updated automatically, add -i to the sed command: sed -i "s/.... This is called in-place editing.


    Test

    Given a file with this content:

    <?php return 0;
    

    Let's see what it returns:

    $ sed "s/0/$(date +%s)/g" file
    <?php return 1372175125;
    
    0 讨论(0)
提交回复
热议问题