Reputation: 2491
I have a input file 1.txt
[email protected]:1802752:2222:
[email protected]:1802756:111113
[email protected]:xxmyaduh:13@;:3A
and I want an output file: out.txt
[email protected]||o||1802752||o||2222:
[email protected]||o||1802756||o||111113
[email protected]||o||xxmyaduh||o||13@;:3A
I want to replace the first two ':' in 1.txt with '||o||', but with the script I am using
awk -F: '{print $1,$2,$3}' OFS="||o||" 3.txt
But it is not giving the expected output. Any help would be highly appreciated.
Upvotes: 2
Views: 166
Reputation: 201
Suppose if we need to replace first 2 occurrence of : use below code
Like this you can change as per your requirement suppose if you need to change for first 7 occurences change {1..2} to {1..7}.
Out put will be saved in orginal file. it wont display the output
for i in {1..2}
> do
> sed -i "s/:/||o||/1" p.txt
> done
Upvotes: 0
Reputation: 241868
Perl solution:
perl -pe 's/:/||o||/ for $_, $_' 1.txt
-p
reads the input line by line and prints each line after processing its///
is similar to substitution you might know from sedfor
in postposition runs the previous command for every element in the following list$_
keeps the line being processedFor higher numbers, you can use for ($_) x N
where N is the number. For example, to substitute the first 7 occurrences:
perl -pe 's/:/||o||/ for ($_) x 7' 1.txt
Upvotes: 4
Reputation: 141
Perl solution also, but I think the idea can apply to other languages: using the limit parameter of split:
perl -nE 'print join q(||o||), split q(:), $_, 3' file
(q quotes because I'm on Windows)
Upvotes: 0
Reputation: 133518
Following sed
may also help you in same.
sed 's/:/||o||/;s/:/||o||/' Input_file
Explanation: Simply substituting 1st occurrence of colon with ||o||
and then 2nd occurrence of colon now becomes 1st occurrence of colon now and substituting that colon with ||o||
as per OP's requirement.
Upvotes: 3