Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using sed to copy lines and delete characters from the duplicates

Tags:

regex

sed

I have a file that looks like this:

@"Afghanistan.png",
@"Albania.png",
@"Algeria.png",
@"American_Samoa.png",

I want it to look like this

@"Afghanistan.png",
@"Afghanistan",
@"Albania.png",
@"Albania",
@"Algeria.png",
@"Algeria",
@"American_Samoa.png",
@"American_Samoa",

I thought I could use sed to do this but I can't figure out how to store something in a buffer and then modify it.

Am I even using the right tool?

Thanks

like image 967
RNs_Ghost Avatar asked Sep 10 '11 01:09

RNs_Ghost


People also ask

How do you remove something from sed?

Deleting line using sed To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.

How do you use sed on a specific line?

Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.

Does sed work line by line?

sed automatically prints each line by default, and then you've told it to print lines explicitly with the “p” command, so you get each line printed twice.


2 Answers

You don't have to get tricky with regular expressions and replacement strings: use sed's p command to print the line intact, then modify the line and let it print implicitly

sed 'p; s/\.png//'
like image 194
glenn jackman Avatar answered Oct 12 '22 14:10

glenn jackman


Glenn jackman's response is OK, but it also doubles the rows which do not match the expression.

This one, instead, doubles only the rows which matched the expression:

sed -n 'p; s/\.png//p'

Here, -n stands for "print nothing unless explicitely printed", and the p in s/\.png//p forces the print if substitution was done, but does not force it otherwise

like image 33
Carles Sala Avatar answered Oct 12 '22 12:10

Carles Sala