Tiago Bruno
Tiago Bruno

Reputation: 413

Rewrite file data using command line Unix utilities

I have a file like this:

 "4" 15356 15422
 "8" 15289 15355
 "7" 14145 15288
 "6" 14071 14139

How can I use awk or another bash tool to rewrite this to

 mm4 15356 15422
 mm8 15289 15355
 mm7 14145 15288
 mm6 14071 14139

Upvotes: 1

Views: 208

Answers (4)

karakfa
karakfa

Reputation: 67507

another alternative

tr -d '"' <file | sed 's/^ / mm/'

 mm4 15356 15422
 mm8 15289 15355
 mm7 14145 15288
 mm6 14071 14139

ps. preserves leading space

Upvotes: 2

Anthony Geoghegan
Anthony Geoghegan

Reputation: 12003

sed would be the simplest and most efficient tool to use. I'd use a regular expression substitution command similar to

sed 's/"\([0-9]*\)"/mm\1/' filename

This searches for a pattern of digits (zero or more) enclosed within double quotes and substitutes them with the matched digits preceded by mm.

While, I only have a copy of GNU sed at hand, the above should work for all versions of sed since it uses only Basic Regular Expressions as defined by POSIX.


If you’re using GNU sed and to want to replace the contents of the file, you could include the -i / --in-place flag:

sed -i.bak 's/"\([0-9]*\)"/mm\1/' filename

This modifies the contents of filename after making a backup copy of it as filename.bak. If you don’t want a backup file, omit the suffix from the -i option.

Upvotes: 2

Cyrus
Cyrus

Reputation: 88776

With GNU sed:

sed -r 's/"([0-9]+)"/mm\1/' file

Output:

 mm4 15356 15422
 mm8 15289 15355
 mm7 14145 15288
 mm6 14071 14139

Upvotes: 2

Brian
Brian

Reputation: 2242

With sed, assuming the file is file:

sed 's/"/mm/;s/"//' file

Upvotes: 2

Related Questions