简体   繁体   中英

sed/awk | single digits to two digits (zero) after a second slash

maybe someone can help me briefly... for example in file.txt...

nw-3001-e0z-4581a/2/5
sed 's/\<[0-9]\>/0&/' file.txt ...
nw-3001-e0z-4581a/02/5

but I want the filled zero only after the second slash, the first number should remain a single digit

thanks in advance! greetz

Could you please try following, written and tested with shown samples. Simply setting field separator and output field separator as / for awk program and then simply adding 0 before 3rd column(if there is only single digit present in it) and print the line.

echo "nw-3001-e0z-4581a/2/5" | awk 'BEGIN{FS=OFS="/"} {$3=sprintf("%02d",$3)} 1'

You can use

awk 'BEGIN{FS=OFS="/"} $NF ~ /^[0-9]$/ {$NF="0"$NF}1' file.txt

Details :

  • BEGIN{FS=OFS="/"} - sets input/output field separator to /
  • $NF ~ /^[0-9]$/ - if last field is a single digit
  • {$NF="0"$NF} - prepend last field with 0
  • 1 - print tjhe result.

Using sed:

sed -rn 's@(^.*/)(.*/)([[:digit:]]{1}$)@\1\20\3@p' <<< "nw-3001-e0z-4581a/2/5"

Split the string into 3 sections using regular expressions (-r). Ensure that the last section has one digit only with [[:digit:]]{1} and substitute the line for the first and second sections, followed by "0" and the third section, printing the result.

$ sed 's:/:&0:2' file
nw-3001-e0z-4581a/2/05

If that's not all you need then edit your question to show more truly representative sample input/output including cases that doesn't work for.

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