私はbashを使用していくつかのデータを複数行ファイルに出力し、各行のデータを次の形式で保存しました。
text1 "text2" text3 integer1,integer2
「空白」は、各行の最初の4つのデータ列を区切ります。カンマは2つの整数を区切ります。 text2 は引用符で囲まれています。
ここで、bashを使用して元のデータファイルの各行を評価し、整数1と整数2を評価するために、別の式を使用して整数1と整数2を新しいデータに置き換えたいと思います。
その後、結果は次のように新しいファイル(元のものと同じ形式)で出力されます。
text1 "text2" text3 Newinteger1,Newinteger2
ベストアンサー1
このコードのためにあなたが混同しなかったことを願っています。 #で始まるコメントをご覧ください。
テストには次の入力ファイルを使用します。
text1 "text2" text3 1,2
this "/usr/strange path with spaces/" works 2,3
次のスクリプトへの入力は次のように与えられますcat input | while ...
。シェルは、スクリプトの最後の行が完了した後にcat
発生する追加のプロセスを防ぐ良い方法を提供します。< input
今覚えておくべき重要なことは、2行目を読む前に1行を解析することです。その行を格納する変数を呼び出しますline
。これはmybuf、firststring、または必要なものです。
それでは始めましょう。
while read -r line; do
# variable line is filled, just echo for debugging
echo "The var line is filled with ${line}."
# Special handling: you can cut off everything starting at the last space
mystrings=${line% *}
# You can also throw away everything up to a space.
# Two # characters for throwing away the largest substring with "* "
myints=${line##* }
# Did it work? Two echoes just checking
echo "mystring=${mystrings}"
echo "myints=${myints}"
# I'll try that strange thing with cutting up a variable again.
# Now I want to cut the myint into two integers
int1=${myints%,*}
int2=${myints#*,}
echo "My results are int1=${int1} and int2=${int2}"
# Some calculation.
# The value of the vars can be used without the $ when used in (( ...))
# Example new values: int1 will be given the original value of int2 + 5,
# int2 will be doubled.
# I did not add checks to see if int1 and int2 are integers
(( int1 = int2 + 5 ))
(( int2 = 2 * int2 ))
# And show the result
echo "${mystrings} ${int1},${int2}"
done < input
何が起こっているのかを正確に知りたい場合は、起動スクリプトを使用できますset -x
(デバッグをオンにしてからもう一度使用してオフにしますset -
)。