Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed only the last match pattern

Tags:

linux

sed

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
like image 815
user2692482 Avatar asked Aug 17 '13 17:08

user2692482


People also ask

How do you match a line at the end of sed?

/[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')

How do you change the last occurrence of a string using sed?

`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.

How can sed be used to identify a pattern?

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.

What does \b mean in sed?

\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 .


1 Answers

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.

like image 77
chooban Avatar answered Sep 30 '22 13:09

chooban