0

I am writing a script that checks files in the directory has shell pid as an extension and rename them in such a way that extension is removed. I have renamed couple of files to add ext using mv filename filename.$$.

I need advice on how to rename them again so that they do not contain the PID.

So far I have witten:

for file in *
do
if [ -s $file ]
then
  if [ $file = *.[0-9] ]
  then
  #mv command
  fi
fi
done

** this is harassing me for past couple of hours **

:(

4

3 に答える 3

3

ここに別のものがあります:

#!/bin/bash

shopt -s extglob nullglob

for i in *.+([[:digit:]]); do
    mv -- "$f" "${f%.*}"
done

トリックは、ドットで終わり、1 つ以上の数字が続くすべてのファイル名に展開されるextglobように (おそらくデフォルトで既にオンになっているため、再度オンにしても害はありません) を使用することです。*.+([[:digit:]])したがって、正規表現は必要ありません。

于 2013-07-09T21:49:49.853 に答える
1

以下を使用して、すべてのファイルの拡張子を削除できます。

for f in *.*
do 
    mv "$f" "${f%.*}"
done

あなたの試みに関して[ .. ]は、グロブと一致することはできません(そして、あなたのグロブは.. そのために使用[[ .. ]]します。のすべての出現箇所も引用する必要があります$file。shellcheck などのツールは、これらのことを自動的に指摘します。

于 2013-07-09T21:25:53.090 に答える
1

純粋なソリューションは次のようになります。

#!/bin/bash

touch a.12345
touch b.23456

for file in *; do
  [[ $file =~ \.[0-9]+$ ]] && echo ${file%$BASH_REMATCH}
done

出力:

a
b

これは、1 つ以上の数字のみが含まれている場合にのみ内線番号を切り捨てます。実際には、有効な PID ではない も切り捨てられますが.0000000000、これは大きな問題ではないかもしれません。

echoコマンドは に置き換えることができますmv "$file" "${file%$BASH_REMATCH}"

于 2013-07-09T21:28:46.217 に答える