sed replace string in a first line

前端 未结 3 1520
自闭症患者
自闭症患者 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

提交回复
热议问题