Search code examples
bashunix

Extract Key/value from file to another file in unix


Hello i have used this code to extract Key/Value from file to another file

BugReports: https://r-forge.r-project.org/tracker/?group_id=194
NeedsCompilation: no
Repository: CRAN
Date/Publication: 2014-03-02 12:40:42" > FichierTest


IFS=":" 
echo $(while read f1 f2
do 
   echo "$f1 ; $f2" 
done < FichierTest) > test.dsc

content of test.dsc:

BugReports ;  https //r-forge.r-project.org/tracker/?group_id=194
NeedsCompilation ;  no
Repository ;  CRAN
Date/Publication ;  2014-03-02 12 40 42

I just want to change the first colon ":" to semi-colon ";" in each line

Many Thanks


Solution

  • Why not just use one-time matching with sed?

    sed -e 's|:|;|' file
    

    Output:

    BugReports; https://r-forge.r-project.org/tracker/?group_id=194
    NeedsCompilation; no
    Repository; CRAN
    Date/Publication; 2014-03-02 12:40:42
    

    Or if you really want to replace everything:

    sed -e 's|:|;|g' file
    

    Output:

    BugReports; https;//r-forge.r-project.org/tracker/?group_id=194
    NeedsCompilation; no
    Repository; CRAN
    Date/Publication; 2014-03-02 12;40;42
    

    Add spaces to replacement if needed.

    By the way, the reason why your output gets spaces instead of colons in some parts is because IFS still has its effect on word splitting. You have to quote your command substitution on it to fix it:

    IFS=":" 
    echo "$(while read f1 f2
    do 
       echo "$f1 ; $f2" 
    done < FichierTest)"
    

    Output:

    BugReports ;  https://r-forge.r-project.org/tracker/?group_id=194
    NeedsCompilation ;  no
    Repository ;  CRAN
    Date/Publication ;  2014-03-02 12:40:42
    

    And the proper way to do it actually is this:

    while IFS=: read -r f1 f2; do 
       echo "$f1 ; $f2" 
    done < FichierTest