Mircsicz
Mircsicz

Reputation: 75

Add quotation marks to a text file

I need to add quotation marks to a list. I'm going to import this list to mailman later.

What I've is a list like this:

SurName Name [email protected]
otherSurName otherName [email protected]

What I need is:

"SurName Name" [email protected]

I expect this to be possible using sed, but can't imagine how.

Upvotes: 3

Views: 470

Answers (5)

user000001
user000001

Reputation: 33397

With awk you could do it like this:

awk '{$1="\""$1; $2=$2"\""}1' file

Test

$ awk '{$1="\""$1; $2=$2"\""}1' file
"SurName Name" [email protected]
"otherSurName otherName" [email protected]

If you also want to handle the case of only two columns do this:

$ awk '{if (NF==2) $1="\""$1"\""; else {$1="\""$1; $2=$2"\""}}1' file
"SurName Name" [email protected]
"otherSurName otherName" [email protected]
"thirdname" [email protected]

Or if know there are only 2 or 3 columns you can do it a bit shorter:

awk '{$1="\""$1;$(NF-1)=$(NF-1)"\""}1' file

If you want to handle lines with no names do this:

awk '{if(NF>2){$1="\""$1; $2=$2"\""}}1' file

demo

$ awk '{if(NF>2){$1="\""$1; $2=$2"\""}}1' file
"SurName Name" [email protected]
"otherSurName otherName" [email protected]
thirdname [email protected]
[email protected]

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185881

Try doing this:

sed -r 's/^(.*) +(.*@.*)/"\1" \2/' file

or

sed -r 's/^(.*) +([^ ]+)$/"\1" \2/' file

Note

this form allow to have 0 to N spaces in the names part, the sed command will take care about that

Upvotes: 2

Daniel Haley
Daniel Haley

Reputation: 52888

Yet another sed option:

sed '{
s/^/"/
s/ \([^ ]*\)$/" \1/
}' inputFile

same thing on a single line:

sed 's/^/"/;s/ \([^ ]*\)$/" \1/' inputFile

Upvotes: 1

Thor
Thor

Reputation: 47249

The first quote is easy, s/^/"/, the second one is a bit trickier, but you can anchor it to the e-mail address with this pattern: s/ *[^@ ]*@[^@]*$/"&/, e.g.:

sed 's/^/"/; s/ *[^@ ]*@[^@]*$/"&/' file

Output:

"SurName Name" [email protected]
"otherSurName otherName" [email protected]

Upvotes: 1

MPogoda
MPogoda

Reputation: 138

If your entire file is ordered like this, you can simply use sed -e 's/^\(.*\) \(.*\) \(.*\)$/"\1 \2" \3/'

Upvotes: 1

Related Questions