Simple find and replace with sed

后端 未结 3 685
独厮守ぢ
独厮守ぢ 2020-12-10 04:46

I\'m trying to replace a number that is in a couple different strings in a text file. Basically it would take the form of

tableNameNUMBER
carNUMBER
         


        
3条回答
  •  醉梦人生
    2020-12-10 05:42

    This should work just fine:

    sed "s/NUMBER/$1/g" myScript.txt > test.txt
    

    The g on the end allows set to replace NUMBER if it appears multiple times on one line.

    In fact, a quick test:

    foo.txt

    carNUMBER
    tableNameNUMBER
    NUMBER
    NUMBERfoo
    
    $ NUMBER=3.14
    $ sed "s/NUMBER/$NUMBER/g" foo.txt
    car3.14
    tableNumber3.14
    3.14
    3.14foo
    

    Isn't that what your sed command is doing?

    If you want to make sure you don't change NUMBER unless it's by itself, use \b around NUMBER:

    $ sed "s/\bNUMBER\b/$NUMBER/g" foo.txt
    carNumber
    tabelNumberNUMBER
    3.14
    NUMBERfoo
    

    If you don't care about the case of the string NUMBER, put an i on the end of the sed command:

    $ sed "s/NUMBER/$NUMBER/gi" foo.txt
    

提交回复
热议问题