0

I have a file with multiple occurances of a string, I need to remove only one of the occurrences using a specific match. I cannot seem to get a good way of doing this, i keep removing all occurrences

sed -i "s/|item2//g"

file format:

 "1234567890|item2",
 "1234567895|item2",
 "3454343345|item1|item2",
 "7854343345|item1|item3",
 "0454343555|item1|item4|item6",

What i need to do is to match the first set of numbers say 3454343345 then after this remove a specific string, like item2.

Output I am trying to get

 "1234567890|item2",
 "1234567895|item2",
 "3454343345|item1|",
 "7854343345|item1|item3",
 "0454343555|item1|item4|item6",
5
  • 3
    You say you want to match with the numbers, then why don't you use the numbers for matching? What should the output look like?
    – Kusalananda
    Feb 19, 2019 at 10:26
  • Yes i tried to pipe using grep, this infact does what i want in the output but i need to do this as a file edit not stdout grep -w "3454343345" file | sed -i "s/|pattern//g" output: "3454343345|pattern2",
    – user4555
    Feb 19, 2019 at 10:30
  • just remove the 'g' from your sed command ....
    – pLumo
    Feb 19, 2019 at 10:33
  • Are your lines quoted like that?
    – Kusalananda
    Feb 19, 2019 at 10:36
  • yes, that is how it is in the file
    – user4555
    Feb 19, 2019 at 10:36

1 Answer 1

1

Try this,

 sed -e '/^"3454343345/ s/item2//' file

"1234567890|item2",
"1234567895|item2",
"3454343345|item1|",
"7854343345|item1|item3",
"0454343555|item1|item4|item6",
  • Replace -e with -i to edit inline, if the output matches your desired result.
2
  • If the placeholder item1 (for example) happens to be the same as the string 3454343345, this would remove the wrong things. You should anchor the pattern to the start of the line. Also, note that this will remove item2 as a substring from anywhere on the line (e.g. from theitem22). Also, again, while "trying" a sed command, never use -i. Doing so would mess up the data if the command happens to be wrong.
    – Kusalananda
    Feb 19, 2019 at 11:01
  • @Kusalananda ur right....
    – Siva
    Feb 19, 2019 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.