Pad numerical values in filename with three digit value using sed

前端 未结 3 514
故里飘歌
故里飘歌 2021-01-22 17:47

I am passing a filename into my bash script and cleaning the name using sed. A few sample files would be:

Test 01.txt
Test v2 01.txt

I would

3条回答
  •  离开以前
    2021-01-22 18:08

    Per your comment, yes I understand about debugging with that method, and that was my guess.

    It's almost as easy, and doesn't require a cleanup step later on to move the closing lines and the "'" char up and down a list like below to debug (as an alternative solution).

    j=$(
      echo "$j" \
      | sed '
        s/\///g
        s/_/ /g
        s/^\.//
        s/\[[^()]*\]//g
        s/([^()]*)//g
        s/#//g
        s/+/\ /g
        s/\.\././g
        s/\&/and/g
        s/\ -/-/g
        s/-\ /-/g
        s/-{2,}/-/g
        s/\.\././g
        s/'"'"'//g
        s/ {2,}/ /g
        s/\ \././g
    ' \
    | awk '/[0-9]/{
       match( $0,/[0-9][0-9]*/ )
       begin=substr($0,1,RSTART); end=substr($0,RSTART+RLENGTH,length($0))
       num=substr($0,RSTART,RSTART+RLENGTH)
       printf("%s%03d%s", begin,num+0, end)
      }'
    )
    

    Edit It may be possible to double-triple up on the escaped single quotes, i.e. \\' or \\\', but I'm going with the tried and true s/'"'"'//g.

    Unless you're using the original bourne shell on Solaris, AIX, HP, or other old-line unixen, join the 1990s ;-) and use the $( ...) construct for command substitution. Backquotes have been deprecated since at least 'The New Kornshell programming Language', published 1995.

    I hope this helps.

提交回复
热议问题