1

I have a file with:

q12 q25 
q13 q15
q78 q13
q42 q54
q13 q12
q12 q74
q45 q25

I want to replace any 12 to 13 and any 13 to 12 :

q13 q25 
q12 q15
q78 q12
q42 q54
q12 q13
q13 q74
q45 q25

how to do this with a simple command?

3 Answers 3

3

Using perl you could avoid making use of a placeholder string to perform the substitutions.

Create a hash of the transformations that are needed and perform a substitution:

perl -pe 'BEGIN{%h=("12" => "13", "13" => "12")} s/(12|13)/$h{$1}/g' inputfile

For your sample input, it'd produce:

q13 q25
q12 q15
q78 q12
q42 q54
q12 q13
q13 q74
q45 q25

Use the -i option to save the changes to the file in-place.

Sign up to request clarification or add additional context in comments.

Comments

3

You could try something like :

sed "s/13/tmp/g;s/12/13/g;s/tmp/12/g" file

You could use -i option if you want to replace inside the file :

sed -i "s/13/tmp/g;s/12/13/g;s/tmp/12/g" file

2 Comments

and be sure that there's no legit tmp in file. Also if you want to do it in place (from and to file), use the -i argument of sed.
@zmo I've edited my answer in the same time ^^ (for the -i option).
1

You can try this:

perl -i.bak -ne '/12/ && !/13/ && s/12/13/g && print; /13/ && !/12/ && s/13/12/g && print; !/12/ && !/13/ && print ' file; cat file
q13 q25 
q12 q25 
q12 q15
q78 q12
q42 q54
q13 q74
q12 q74
q45 q25

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.