5

I have a large text file with words. Every word is on a single line (typical wordlist).

I want to replace all characters "o" with the number "0" in every word, and the new formed word to be pasted on the next line after the original word.

For example, if we have this two in the list:

dog
someone

After the manipulation, our file should looks like this:

dog
d0g
someone
s0me0ne

How this can be done with GNU tools like sed or awk?

  • I hope you don't intend to create passwords that way ;) – Olivier Dulac Sep 3 '14 at 16:58
11

You can use sed:

sed -i -e 'p' -e 's/o/0/g' file

Explanation:

  • -i: activates in-place editing of the file
  • -e 'p': just pastes the line
  • -e 's/o/0/g': replaces o with 0 and pastes the altered line

And if you want an awk solution:

awk '1;gsub("o", "0")' file >new_file
  • You may also want to change the awk statement to awk '1;gsub("o", "0")' file so that it does not print two of lines where the o is not changed – user78605 Sep 2 '14 at 13:05
7

chaos' answer is good if every line matches. But if some lines don't contain a o, they'll be duplicated.
For example:

$ echo -e 'foo\nbar' | sed -e 'p' -e 's/o/0/g'
foo
f00
bar
bar

 

Here are some other solutions which don't duplicate lines:

$ echo -e 'foo\nbar' | sed -e '/o/ p; s//0/g' 
foo
f00
bar

 

$ echo -e 'foo\nbar' | perl -pe '/o/ && print; s/o/0/g'
foo
f00
bar

 

$ echo -e 'foo\nbar' | awk '{ print } /o/ { gsub(/o/, "0"); print }' 
foo
f00
bar
  • You don't need o in s/o/0/g, just sed -e '/o/ p; s//0/g'. – cuonglm Sep 2 '14 at 16:42
  • it may not be needed, but I prefer the clarity – Patrick Sep 2 '14 at 16:45
3

Another sed solution:

sed -ne 'p;s/o/0/pg' file

$ printf '%s\n%s\n' 'foo' 'bar' | sed -ne 'p;s/o/0/pg'
foo
f00
bar

Explanation

  • -n option causes sed suppress the default output.
  • p command write the pattern space to standard output.
  • s/o/O/pg replaces all occurences (g flag) of o with 0, only write pattern space to standard output if a replacement was made (p flag).
  • Why not just do sed 'p;s/o/0/g' ? – user78605 Sep 3 '14 at 10:08
  • @Jidder: It will duplicate line without match, like bar in example. – cuonglm Sep 3 '14 at 10:13

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.