私はこの変数を持っています:
A="Some variable has value abc.123"
この値を抽出する必要がありますabc.123。これはbashで可能ですか?
最も単純なのは
echo $A | awk '{print $NF}'
編集:これがどのように機能するかの説明...
awkデフォルトで区切り文字として空白を使用して、入力をさまざまなフィールドに分割します。代わり5にハードコーディングするNFと、入力の5番目のフィールドが出力されます。
echo $A | awk '{print $5}'
NFawk現在のレコードのフィールドの総数を示す組み込み変数です。文字列には5つのフィールドがあるため、以下は数値5を返します"Some variable has value abc.123"。
echo $A | awk '{print NF}'
と組み合わせる$とNF、文字列に含まれるフィールドの数に関係なく、文字列の最後のフィールドが出力されます。
はい; これ:
A="Some variable has value abc.123"
echo "${A##* }"
これを印刷します:
abc.123
(この表記は、 Bashリファレンスマニュアルの§3.5.3「シェルパラメータの拡張」で説明されています。)${parameter##word}
Some examples using parameter expansion
A="Some variable has value abc.123"
echo "${A##* }"
abc.123
Longest match on " " space
echo "${A% *}"
Some variable has value
Longest match on . dot
echo "${A%.*}"
Some variable has value abc
Shortest match on " " space
echo "${A%% *}"
some
Read more Shell-Parameter-Expansion
値がどこから始まるかをどうやって知るのですか?常に5番目と6番目の単語である場合は、次のように使用できます。
B=$(echo $A | cut -d ' ' -f 5-)
これは、cutコマンドを使用して、単語の区切り文字として単純なスペースを使用して、行の一部を切り取ります。
The documentation is a bit painful to read, so I've summarised it in a simpler way.
Note that the '*' needs to swap places with the ' ' depending on whether you use # or %. (The * is just a wildcard, so you may need to take off your "regex hat" while reading.)
${A% *} - remove shortest trailing * (strip the last word)${A%% *} - remove longest trailing * (strip the last words)${A#* } - remove shortest leading * (strip the first word)${A##* } - remove longest leading * (strip the first words)Of course a "word" here may contain any character that isn't a literal space.
You might commonly use this syntax to trim filenames:
${A##*/} removes all containing folders (e.g. /usr/bin/git -> git)${A%.*} removes the last extension (e.g. archive.tar.gz -> archive.tar) - just be wary of things like my.path/noextAs pointed out by Zedfoxus here. A very clean method that works on all Unix-based systems. Besides, you don't need to know the exact position of the substring.
A="Some variable has value abc.123"
echo $A | rev | cut -d ' ' -f 1 | rev
# abc.123