sed replace string in a first line

前端 未结 3 1518
自闭症患者
自闭症患者 2021-01-17 11:42

How can I replace a string but only in the first line of the file using the program \"sed\"?

The commands s/test/blah/1 and 1s/test/blah/ d

相关标签:
3条回答
  • 2021-01-17 11:59

    This will do it:

    sed -i '1s/^.*$/Newline/' textfile.txt
    

    Failing that just make sure the match is unique to line one only:

    sed -i 's/this is line one and its unique/Changed line one to this string/' filename.txt
    

    The -i option writes the change to the file instead of just displaying the output to stdout.

    EDIT:

    To replace the whole line by matching the common string would be:

    sed -i 's/^.*COMMONSTRING$/Newline/'
    

    Where ^ matches the start of the line, $ matches the end of the line and .* matches everything upto COMMONSTRING

    0 讨论(0)
  • 2021-01-17 12:10

    this replaces all matches, not just the first match, only in the first line of course:

     sed -i '1s/test/blah/g' file
    

    the /g did the trick to replace more than one matches, if any exists.

    0 讨论(0)
  • 2021-01-17 12:11

    This might work for you (GNU sed):

    sed -i '1!b;s/test/blah/' file
    

    will only substitute the first test for blah on the first line only.

    Or if you just want to change the first line:

    sed -i '1c\replacement' file 
    
    0 讨论(0)
提交回复
热议问题