Swapping strings in a file

Hi,

  How to swap two strings in a file ? 

Ex: "ABC" to be swapped with "XYZ"
"ABC" and "XYZ" donot occur in a same line .
String has ""

Regards
Tej

Usually you could use sed or perl. If you have GNU sed which has the -i flag, you could use sed. Else perl is good.

sed -i -e "s/ABC/XYZ/g"
perl -p -i -e "s/ABC/XYz/g"

Give an example atleast ...

Example is ,
I have a file test.txt, in which I need to swap "ABC" with "XYZ". I cannot use replace because I still have to retain both the strings in the same file.

File looks like this:

"DEF", "678", "ABC", "GHI", "KLM", ...."123",
"345", XYZ", "MNO", "PQR", 

I need to swap "ABC" with "XYZ"

Regards
Tej

---------- Post updated at 04:12 AM ---------- Previous update was at 03:48 AM ----------

I tried using perl -p -i -e "s/ABC/XYz/g" test.txt in the command line. Command is replacing but not swapping these two strings

try this

 
$ cat inf
"DEF", "678", "ABC", "GHI", "KLM", ...."123",
"345", XYZ", "MNO", "PQR",

$ cat inf | sed 's/ABC/TMP/g;s/XYZ/ABC/g;'| sed 's/TMP/XYZ/g'
"DEF", "678", "XYZ", "GHI", "KLM", ...."123",
"345", ABC", "MNO", "PQR",

I tried using this command, swapping is still not happening.
File is unchanged

a simple & ugly method of doing it, which may only work for the given example.

18:18:33 : tmp :cat > t
"DEF", "678", "ABC", "GHI", "KLM", ...."123",
"345", XYZ", "MNO", "PQR",
18:18:47 : tmp :cat t
"DEF", "678", "ABC", "GHI", "KLM", ...."123",
"345", XYZ", "MNO", "PQR",
18:18:49 : tmp :perl -i t.pl t
18:18:53 : tmp :cat t
"DEF", "678", "XYZ", "GHI", "KLM", ...."123",
"345", ABC", "MNO", "PQR",
18:18:55 : tmp :cat t.pl
undef $/;

$_=<>;

s/(ABC)(.*)(XYZ)/\3\2\1/s;
print;

Or you could use a hash. Set the key-value pairs, search for any of the keys, substitute by the corresponding value.

$
$ cat -n test.txt
     1  "DEF", "678", "ABC", "GHI", "KLM", "123",
     2  "345", "XYZ", "MNO", "PQR",
     3  "PQR", "123", "XYZ", "GHI", "KLM", "123",
     4  "LMN", "456", "ABC", "GHI", "KLM", "123",
$
$ perl -lne 'BEGIN {%x=qw(ABC XYZ XYZ ABC)} s/(ABC|XYZ)/$x{$1}/g; print' test.txt
"DEF", "678", "XYZ", "GHI", "KLM", "123",
"345", "ABC", "MNO", "PQR",
"PQR", "123", "ABC", "GHI", "KLM", "123",
"LMN", "456", "XYZ", "GHI", "KLM", "123",
$
$

tyler_durden

just parsed it to another file with >

or you can use -i parameter in sed

sed -i 's/ABC/TMP/g;s/XYZ/ABC/g;' input_file | sed -i 's/TMP/XYZ/g' input_file

:smiley: