2

I want to change in file in each line the last match to the XXXX Given the file format:

"192.xx2" "someting" "another2321SD" 

I want to have:

"192.xx2" "someting" "XXXX" 

only using sed My solution:

sed -r 's/"(?:.(?!".+"))+$/XXXX/' file
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

2 Answers2

2

Remember what was there before the last pair of double quotes in a capture.

sed -r 's/^(.*)"[^"]*"$/\1"XXXX"/'
choroba
  • 231,213
  • 25
  • 204
  • 289
1

Please bear in mind that

To mask all content in between the last pair of double quotation marks, you can use

sed -r 's/(.*)".*"/\1"XXXX"/' file
sed 's/\(.*\)".*"/\1"XXXX"/' file

See the sed demo:

s='"192.xx2" "someting" "another2321SD"'
sed -r 's/(.*)".*"/\1"XXXX"/' <<< "$s"
# => "192.xx2" "someting" "XXXX"
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • At https://stackoverflow.com/a/66778854/3220113 you ask for an improvement. I don't know, if my answers are better but you could also assume that the `"` is the last character of the input: `sed 's/"[^"]*"$/"XXXX"/' <<< "$s"`. When you are not sure (or when you are charged for every double quote you use), you can use `rev < <(sed -r 's/[^"]+/XXXX/' <( rev <<<"$s"))`. Worse seems to be `awk -F '"' 'BEGIN { OFS="\""} { $(NF-1)="XXXX"; print }' <<< "$s"`. – Walter A Mar 24 '21 at 23:11
  • @WalterA Thanks, Walter. Assuming the last quoted part is really close to the end of string, I think the current approach should be already good enough. I did not consider `awk` due to question tags, I think there can be many more assumptions then. – Wiktor Stribiżew Mar 24 '21 at 23:35