- / tmp/txtをファイルします
- ファイルの内容:aaa aaa aaa _bbb bbb bbb
- ファイル/tmp/ txt_leftを保存する必要があります:aaa aaa aaa
- ファイル/tmp/ txt_rightを保存する必要があります:bbb bbb bbb
!!! 変数を使用せずに解決策を探す注意!!!
!!! 変数を使用せずに解決策を探す注意!!!
awk -F '_' '{print $1> "/tmp/txt_left"; print $2 > "/tmp/txt_right" }' /tmp/txt
より短く、より速く:
sed -ne $'h;s/_.*$//;w /tmp/txt_left\n;g;s/^.*_//;w /tmp/txt_right' /tmp/txt
説明: 次のように記述できます。
sed -ne '
h; # hold (copy current line in hold space)
s/_.*$//; # replace from _ to end of line by nothing
w /tmp/txt_left
# Write current line to file
# (filename have to be terminated by a newline)
g; # get (copy hold space to current line buffer)
s/^.*_//; # replace from begin of line to _ by nothing
w /tmp/txt_right
# write
' /tmp/txt
これは実際の変数ではありません。最初の引数要素を使用してジョブを実行し、終了したら引数リストを復元します。
set -- "$(</tmp/txt)" "$@"
echo >>/tmp/txt_right ${1#*_}
echo >>/tmp/txt_left ${1%_*}
shift
引数行の最初の場所で文字列のシフトを解除し、引数行よりも操作を行うので、$1
変数shift
は使用されず、問題なく、引数行は元の状態に戻ります
...そしてこれは純粋なbash
解決策です;-)
アンダースコアにスリットを入れて、線をカットしてみることができます
Cat /tmp/txt | cut -d_ -f 1 > txt_left
bash プロセス置換、tee、およびカットを使用する:
tee -a >(cut -d _ -f 0 > /tmp/txt_left) >(cut -d _ -f 1 >/tmp/txt_right) < /tmp/txt