I have a input file 1.txt
joshwin_xc8@yahoo.com:1802752:2222:
ihearttofurkey@yahoo.com:1802756:111113
www.rothmany@mail.com:xxmyaduh:13@;:3A
and I want an output file: out.txt
joshwin_xc8@yahoo.com||o||1802752||o||2222:
ihearttofurkey@yahoo.com||o||1802756||o||111113
www.rothmany@mail.com||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.
Perl solution:
perl -pe 's/:/||o||/ for $_, $_' 1.txt
-p
reads the input line by line and prints each line after processing it s///
is similar to substitution you might know from sed for
in postposition runs the previous command for every element in the following list $_
keeps the line being processed For 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
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.
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.