各行の奇数単語と偶数単語を置き換える方法は?

各行の奇数単語と偶数単語を置き換える方法は?

あるファイルから奇数文字と偶数文字列を置き換え、別のファイルに保存するbashスクリプトがあります。

#!/bin/bash

infile="inputfile"
outfile="outputfile"

{
while read -r odd && read -r even
do
    echo "$even"
    echo "$odd"
    unset odd
done < "$infile"

# in case there are an odd number of lines in the file, print the last "odd" line read
if [[ -n $odd ]]; then
    echo "$odd"
fi
} > "$outfile"

奇数と偶数を変える方法性格ファイルの各行に?

例:

入力ファイル:

one two three four five six
apple banana cocoa dish fish nuts

結果ファイル:

two one four three six five
banana apple dish cocoa nuts fish

ベストアンサー1

使用幸せ(以前のPerl_6)

raku -ne 'put .words.rotor(2).map(*.reverse);'  

または

raku -ne '.words.rotor(2).map(*.reverse).put;'

または

raku -ne '.words.rotor(2)>>.reverse.put;' 

入力例:

one two three four five six
apple banana cocoa dish fish nuts

出力例:

two one four three six five
banana apple dish cocoa nuts fish

上記は、Perlシリーズのプログラミング言語であるRakuで書かれた答えです。つまり、raku1行ずつ自動印刷ではなくフラグを使用してコマンドラインから呼び出されます。または、コマンドラインフラグを-ne使用すると、各行はRakuの「テーマ変数」(Perlでは「テーマ変数」とも呼ばれます)とも呼ばれるにロードされます。先行点は、トピック変数に次の方法が適用されることを示す省略形です。連続したメソッドはドット演算子とともに連結され、各メソッドは順番に入力データを変換します。-ne-pe$_$_.$_.$_.

これらの方法を見ると、1行ずつ入力された内容がスペースで区切られ、次に単語のペアwordsrotorまとめられていることがわかります(つまり、2引数が提供されます)。関数名はrotor多少あいまいかもしれませんが、データオブジェクトの個々の要素が繰り返されるかrotor編集され、一緒にグループ化/集計されるという意味になります。 -ing 後、rotor各ペアは使用および適用される機能によって個別に処理されます。最後に、出力は次のように印刷されます。mapreverseput

上記のコード(rotorデフォルトを使用)は、最後の「不完全な要素のセット」を削除します。最後に「不完全な要素セット」を維持するには、呼び出しを変更してrotorTrueパラメータを追加するpartialか、batch同じ意味の次を使用します。

raku -ne 'put .words.rotor(2, partial => True).map(*.reverse);' 

これは次のとおりです。

raku -ne 'put .words.rotor(2, :partial).map(*.reverse);'

これは次のとおりです。

raku -ne 'put .words.batch(2).map(*.reverse);'

https://raku.org

おすすめ記事