I would like to sed
only the last match pattern of a text file.
input file:
boy
boy
girl
boy
output file:
boy
boy
girl
boys
/[a-zA-Z]\+$/{} means apply whatever comes inside the curlies to lines that match the regex. Inside the curlies, N means "append the next line to the active buffer" (what sed calls the 'pattern space')
`tac` command is used to reverse the content of the file. `tac` command is used with the `sed` command in the following command to replace the last occurrence of '2019' with the word, '2017'. The following output will appear after running the commands. Here, the year value, '2019' appears three times in the file.
If any word appears multiple times in a file then the particular occurrence of the word in each line can be replaced by using `sed` command with the occurrence number. The following `sed` command will replace the second occurrence of the searching pattern in each line of the file, python. txt.
\b marks a word boundary, either beginning or end. Now consider \b' . This matches a word boundary followed by a ' . Since ' is not a word character, this means that the end of word must precede the ' to match. To use \b to match at beginnings of words, reverse the order: '\b .
One method would be to reverse the file, replace only the first match, and then reverse it back again.
tac <file> | sed '1 s/boy/boys/' | tac | sponge <newfile>
tac will "concatenate and print files in reverse". sponge will "soak up standard input and write to a file". It's in the "moreutils" package on debian.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With