简体   繁体   中英

Adding delimiters to CSV column

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.

POSIX Awk:

{
  for (x = 1; x < length; x += 2) {
    printf "%s%s", substr($0, x, 2), x == length - 1 ? RS : ":"
  }
}

GNU sed

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

你可以尝试一下

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

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM