Reputation: 29
I need help writing a script that will add :
between two characters in a single column csv file. Based on my research awk looks like the tool I need but I am stuck trying to merge two solutions and I am looking for help.
My csv column involves MAC addresses without delimiters
000000000000 111111111111 222222222222
I need the output to convert to
00:00:00:00:00:00 11:11:11:11:11:11 22:22:22:22:22:22
and I have about 1500 of these in a csv file i would like to convert.
I found a solution to add the :
for every two characters:
add=000000000000
echo $add | awk '{for(i=1;i<=length($0);i+=2){printf("%s:",substr($0,i,2))}}'|awk '{sub(/:$/,"")};1'
00:00:00:00:00:00
I also found an example that will read from column 1:
awk -F "\"*,\"*" '{print $1}' myfile.csv
However, I need help reading each row in the column, applying the script to add the :
and then write the file to column 2 or a whole new file it doesn't matter to me.
Upvotes: 2
Views: 248
Reputation: 1
POSIX Awk:
{
for (x = 1; x < length; x += 2) {
printf "%s%s", substr($0, x, 2), x == length - 1 ? RS : ":"
}
}
Upvotes: 3
Reputation: 77085
Another way with sed
:
sed 's/../:&/2g' file
$ cat file
000000000000
111111111111
222222222222
$ sed 's/../:&/2g' file
00:00:00:00:00:00
11:11:11:11:11:11
22:22:22:22:22:22
Upvotes: 0
Reputation: 37569
sed -e 's/\([0-9][0-9]\)/\1:/g' -e 's/:$//' file
input:
000000000000
111111111111
222222222222
output:
00:00:00:00:00:00
11:11:11:11:11:11
22:22:22:22:22:22
Upvotes: 3
Reputation: 51593
You might give a try to
awk '{print gensub("([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])","\\1:\\2:\\3:\\4:\\5","g")}' INPUTFILE
Upvotes: 1
Reputation: 67211
Perl will also do and changes the file inplace which awk does not do:
perl -pi -e 's/(..)/$1:/g;s/:$//g' your_file
Tested:
> cat temp
000000000000
111111111111
222222222222
> perl -pe 's/(..)/$1:/g;s/:$//g' temp
00:00:00:00:00:00
11:11:11:11:11:11
22:22:22:22:22:22
>
If you insist on awk :
awk '{gsub("..","&:");print substr($0,0,length($0)-1)}' your_file
Upvotes: 0