简体   繁体   中英

bash scripting: how to move a string before .<dot> for each line in a file

file contains:

compat-db.x86_64                      4.6.21-17.el6                          
chkconfig.x86_64                      1.3.49.5-1.el6

I would like to add prefix - before 4.6.21-17.el6 and move this before . with bash scripting.

So the output should be:

compat-db-4.6.21-17.el6.x86_64
chkconfig-1.3.49.5-1.el6.x86_64

Any suggestions how to achieve this?

awk solution:

awk '{ sub(/\./,"-"$2".",$1); print $1 }' file

The output:

compat-db-4.6.21-17.el6.x86_64
chkconfig-1.3.49.5-1.el6.x86_64

GNU-sed solution:

sed 's/\.\(.*\)[[:space:]]\+\(.*\)/-\2.\1/'
  • \\. matches a dot literally
  • [:space:] is a POSIX class, in a character class, it matches any whitespace character
  • \\+ means "at least once"
  • \\(...\\) is used for capturing

BSD Sed & GNU 解决方案:

sed -E 's!^([^\s\.]*)(\.[a-Z0-9_^\s]*)[\s]*([^\s]*)[\s]*$!\1-\3\2!g;s! !!g' < yourfile.txt

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