A line starting with Fred Flintstone shall be appended with some string.
Look for specified occurrence of Fred Flintstone and append it.
How do I use this command for anyone of the occurrences of such a pattern?
I tried
sed '/Fred Flintstone/ s/$/ someString/2' filename
Apparently the above one isn't working.
It works well for all occurrences, but not a specific occurrence.
(Say I want to replace first or second or third [any one of them])
Example File1:
Fred Flintstone
Johnson Stone
Fred Flintstone
Fred Flintstone
Michael Clark
Desired Output File1:
Fred Flintstone
Johnson Stone
Fred Flintstone someString
Fred Flintstone
Michael Clark
Best Answer
Although you've mentioned
sed
, these are sort ofawk
-y tasks:-v pat="Fred Flintstone"
saves the Regex pattern to match as variablepat
to be used insideawk
expressions$0 ~ pat
checks the record againstpat
for a match; if matched, thecount
variable is increased by 1 and ifcount
is 2 the record is reset as having the current content plussomeString
({count++; if (count == 2) { $0 = $0" someString" ;} ;}
)1 is an idiom; as it is truthy, all the records would be printed
Example: