'Cut part of path in CSV without deleting rest of csv file

I have CSV file which looks like that:

/users/my/temporaryprojects/project1/Assets/file.ttf,Arial Unicode MS,Regular,Arial Unicode MS,ArialUnicodeMS,Version 1.01x,Monotype
/users/my/temporaryprojects/project2/Assets/file2.ttf,Arial Unicode MS,Regular,Arial Unicode MS,ArialUnicodeMS,Version 1.01x,Monotype

I need to change the path to users/my/temporaryprojects/project1 + rest of CSV data, users/my/temporaryprojects/project2 + rest of CSV data etc... . I was trying to do different bash scripts like

cut -d'/' -f 5- newTTF-Projects-INFO.csv >> ONETTF-Projects-INFO.csv

But unfortunately every time the script is deleting everything which is after the first comma separated value:

/users/my/temporaryprojects/project1
/users/my/temporaryprojects/project2

I need it to be in this format:

/users/my/temporaryprojects/project1, Arial Unicode MS,Regular,Arial Unicode MS,ArialUnicodeMS,Version 1.01x,Monotype
/users/my/temporaryprojects/project2, Arial Unicode MS,Regular,Arial Unicode MS,ArialUnicodeMS,Version 1.01x,Monotype

I need to shorter the path to file which is on the first place and leave as it is every other data. I know that every time I need only 4 first parts of the value. I was trying to do this all night long with "cut", "sed", "awk" but I don't have my result. Every method is deleting values after the first comma. Could somebody help me? I did not find any answer to my question. The file to edit has a lot of rows like the one in example.



Solution 1:[1]

  • backreferences-capable regex engine not needed at all for this barebones awk-solution

  • straight up cleaning FS to OFS

CODE

echo "${input}" | 

mawk NF=NF FS='[/][^,\\/]*[/][^,\\/]*[,]' OFS=', '

           or simply just

gawk NF=NF FS='[/][^,/]*[/][^,/]*[,]' OFS=', '

OUTPUT

/users/my/temporaryprojects/project1, Arial Unicode MS,Regular,Arial Unicode MS,ArialUnicodeMS,Version 1.01x,Monotype
/users/my/temporaryprojects/project2, Arial Unicode MS,Regular,Arial Unicode MS,ArialUnicodeMS,Version 1.01x,Monotype

Solution 2:[2]

awk -F, -v level="2" '
  function dirname(f,l) {
    s = ""; n=split(f,a,"/");
    for (i=2; i<=n-l; i++) {  s = s "/" a[i] }
    return s
  }
  function basename(f) {
    n=split(f,a,"/");return a[n]
  }
  BEGIN{ OFS=FS }
  {$1=dirname($1,level); $2=" "$2}1
' input_file

/users/my/temporaryprojects/project1, Arial Unicode MS,Regular,Arial Unicode MS,ArialUnicodeMS,Version 1.01x,Monotype
/users/my/temporaryprojects/project2, Arial Unicode MS,Regular,Arial Unicode MS,ArialUnicodeMS,Version 1.01x,Monotype

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RARE Kpop Manifesto
Solution 2 ufopilot