Simple find and replace with sed

后端 未结 3 684
独厮守ぢ
独厮守ぢ 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:23

    to replace 1111 to 2222 you should probably try

    cat textfile.txt | sed -e 's/1111/2222/g'
    

    or

    cat textfile.txt | sed -e 's/1111/2222/g' > output.txt
    

    or

    NUMBER=1111 ; NEWNUMBER=2222; cat textfile.txt | sed -e "s/$NUMBER/$NEWNUMBER/g"
    

    There's no need to create separate script for such trivial task. Note "-e" switch for sed, "g" appended at the end of quoted command, and the difference between single and double quotes.

    0 讨论(0)
  • 2020-12-10 05:26

    Since you've stated you're new to this, I'm going to first answer some problems that you haven't asked.

    Your shebang is wrong

    The first bytes of your script should be #! (a hash and an exclamation mark; referred to as a shebang). You have #1 (hash-one), which is gibberish. This shebang line tells the system to use bash to interpret your file (i.e. your script) when executed. (More or less. Technically speaking, it's actually given to env, which finds bash before handing it over.)

    Once you've fixed up the shebang, set the permissions on the script to let the system know it's executable:

    $ chmod a+x test.sh
    

    Then run it like so:

    $ ./test.sh 123456
    

    As @gokcehan also commented, running your script with sh ... when you have a shebang is redundant, and isn't preferable for other reasons.


    As for what you were asking, you can easily test your regex replacement:

    $ echo tableNameNUMBER | sed "s/NUMBER/123456/"
    tableName123456
    

    And it seems to work just fine.

    Note: The preceding $ merely denotes that I typed it into my console and isn't part of the actual command.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题