简体   繁体   中英

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

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

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